Python Environment Variables: os.environ, dotenv, and Pydantic
How to read, set, and manage environment variables in Python. Covers os.environ, python-dotenv, Pydantic Settings, Django, and Flask patterns.
Last updated:
Frequently Asked Questions
How do I read an environment variable in Python?
Use os.environ["KEY"] to read a variable (raises KeyError if missing) or os.getenv("KEY", "default") to read with a fallback default value. Import os first.
How do I use .env files in Python?
Install python-dotenv (pip install python-dotenv) and call load_dotenv() at the top of your entry file before accessing any environment variables. It reads .env and sets the values in os.environ.
What is Pydantic Settings?
Pydantic Settings (pydantic-settings package) provides type-safe environment variable parsing. Define a class extending BaseSettings with typed fields, and Pydantic automatically reads from environment variables, validates types, and provides defaults.
Stay up to date
Get notified about new guides, tools, and cheatsheets.
Related Guides
dotenv Not Loading? Step-by-Step Debugging Guide
Fix environment variables not loading from .env files. Covers Node.js, Python, Docker, file path issues, syntax errors, load order, and production gotchas.
Node.js Environment Variables: process.env, dotenv & --env-file
How to use environment variables in Node.js. Covers process.env, dotenv, Node 20.6+ --env-file flag, NODE_ENV, type-safe validation with zod, and cross-platform support.
The Complete .env File Syntax Reference
Definitive reference for .env file syntax: quoting rules, comments, multiline values, variable expansion, and differences across Node.js, Python, Ruby, Go, and Docker Compose.