Managing Python Application Configuration Across Multiple Environments
This article explains how to structure Python projects so that configuration can be cleanly switched between development, testing, staging, and production environments using packages, __init__.py tricks, environment variables, and dynamic imports, following principles from the Twelve‑Factor App.
The guide starts by reminding that Python modules and packages map directly to the filesystem layout, and that an empty __init__.py turns a directory into a package.
It warns against putting executable code in __init__.py because it runs on import, but demonstrates a simple experiment where adding sys.exit() causes the interpreter to quit as soon as the package is imported.
Next, it discusses the need for multiple deployment environments (development, test, staging, production) and aligns the approach with the Twelve‑Factor methodology, recommending that static configuration lives in code while dynamic or secret values are kept out of version control.
The article proposes using a single environment variable (e.g., ENV ) to indicate the current runtime context, similar to RACK_ENV , RAILS_ENV , or NODE_ENV in other ecosystems.
It then shows a concrete directory layout: a config package containing common.py (shared settings), and an environments sub‑package with development.py , production.py , staging.py , etc., each overriding only what differs.
In config/__init__.py the implementation imports importlib , reads the ENV variable (defaulting to development ), loads the corresponding module with importlib.import_module , and updates the package globals with the environment‑specific settings.
A real‑world example from the author’s own site illustrates how the configuration files are organized, how secrets like SENTRY_DSN are kept only in production, and how Redis connections are built from environment‑specific values.
The conclusion lists practical benefits: unlimited environment flexibility, easy switching between modes, clear visibility of overrides for new team members, per‑developer local settings without polluting shared config, and reduced reliance on large CLI‑passed key/value maps.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.