How can I access environment variables in Python?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Environment variables are a standard way to pass configuration into a Python program without hardcoding values into source files. They are commonly used for secrets, API endpoints, feature flags, and runtime settings that change between development, testing, and production.
Reading Environment Variables
The standard library module for this is os. The most common APIs are os.environ and os.getenv.
Use os.environ when you want dictionary-like access:
This raises KeyError if the variable does not exist, which is useful when the variable is mandatory.
Use os.getenv when a missing variable is acceptable:
This returns the default value if the variable is unset. In practice, many applications combine both styles:
- required secrets use
os.environ[...] - optional settings use
os.getenv(..., default)
A Practical Configuration Pattern
It is usually better to read environment variables once and normalize them in one place instead of scattering os.getenv throughout the codebase.
For example:
This approach has two benefits:
- startup fails early if a required variable is missing
- type conversion happens in one predictable place
Without that step, it is easy to forget that environment variables are always strings and accidentally compare "8000" to 8000 or "false" to False.
Setting and Deleting Variables Inside Python
You can also modify the current process environment:
This only affects:
- the current Python process
- child processes started after the change
It does not permanently update your shell, system settings, or future terminal sessions.
That distinction matters a lot. Developers often expect os.environ["X"] = "1" to change their terminal environment globally, but it does not.
Passing Variables to Child Processes
When you launch another process from Python, it inherits environment variables unless you override them.
This is useful for tests, build scripts, and wrappers around CLI tools.
If you do not pass env=..., the child process usually inherits the current environment automatically. Passing a copied and modified dictionary gives you tighter control.
Using .env Files During Development
In local development, many teams store configuration in a .env file and load it with python-dotenv. That is convenient, but it is still separate from the operating system environment until your program loads it.
Example .env file:
Loading it in Python:
This is a development convenience, not a replacement for secure secret management in production. In production systems, environment variables are often injected by process managers, containers, CI pipelines, or cloud platforms.
Security and Validation
Environment variables are better than hardcoding secrets in source files, but they are not automatically safe. They can still leak through:
- debug logs
- process inspection
- accidental dumps of configuration objects
A good pattern is to validate them and avoid printing sensitive values:
Notice that the code confirms success without exposing the secret itself.
Common Pitfalls
The most common mistake is forgetting that all environment variables arrive as strings. If you need booleans, integers, or lists, convert them explicitly.
Another mistake is using os.environ["NAME"] for optional settings. That raises KeyError and can make local development annoying. Use os.getenv with a default when the value is optional.
Developers also assume changes to os.environ persist after the script ends. They do not. The change is local to the current process and its children.
Finally, avoid committing .env files with real secrets. A .env file is convenient, but it is still plain text and should be handled carefully.
Summary
- Use
os.environfor required variables andos.getenvfor optional ones. - Environment variables are always strings, so convert them to the types you need.
- Changes to
os.environaffect only the current process and child processes. - '
.envfiles are useful for development when paired withpython-dotenv.' - Validate configuration early and avoid printing secret values into logs.

