For a project with one development environment and one production environment, would you use a .env file, Pydantic settings, or plain environment variables? How do you handle secrets and defaults without making config messy over time?
How do you keep config manageable in a small Python project?
Answers
I'd start with a single config.py that reads environment variables once at startup. Check that required values are present and parse the types there, then pass the resulting settings into the rest of the app.
That works with plain os.environ and avoids another dependency. The main thing to watch is defaults: a convenient development database setting should not silently become the production setting when a variable is missing.
Reply to this answer
If Pydantic is already in the project, pydantic-settings is a nice fit. You get a settings class with type conversion and validation, so missing or malformed values can fail at startup instead of halfway through a request.
It can read a dotenv file for development and environment variables supplied by the deployment platform in production. SecretStr can also help prevent secrets from showing up in ordinary representations, though it is not a substitute for secure secret storage.
Reply to this answer
For a small app, python-dotenv and a local .env file are pretty straightforward. Keep the real file out of version control and commit a .env.example with the expected keys and blank secret values.
Production depends on the deployment setup. A cloud secret vault or a platform's secret configuration can supply values there, rather than copying the development file onto the server.
Reply to this answer
Another option is to separate the boring defaults from the secrets. Put non-secret defaults in a committed config.toml, read it with tomllib, and reserve environment variables for secrets and deployment-specific overrides.
That gives you a visible record of the defaults without stuffing everything into .env. Document which environment variables are required so production setup doesn't depend on guessing.
Reply to this answer
If dev and production need meaningfully different rules, an explicit environment setting can select separate settings classes with a shared base. Load .env only for development and require production values from the deployment environment.
That may be more structure than a tiny app needs, but it makes it harder to accidentally carry development defaults into production.
Reply to this answer
Add your answer
Answers are reviewed before publication.
2h!cobblewhisk_647:
You can also pass the settings object into the components that need it. That makes test overrides easier without having every module read the environment independently.