🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeHow to Work with Environment Variables in Python: A Guide

Different stages of a project can call for different settings, from a developer’s computer to a deployed program. Environment variables are named text values that a program can read from the environment where it runs.
In this piece, I’ll show how to read environment variables in Python and load local values from a .env file.
TL;DR
Use Python’s os module to read and set environment variables, then validate values before your application depends on them.
- Use os.environ[“NAME”] for a required value and os.getenv(“NAME”, default) for an optional one.
- Environment values are strings, so parse and validate numbers and booleans.
- Use python-dotenv to load a local .env file during development, and keep secret files out of version control.
What Are Environment Variables in Python?
An environment variable is a named string supplied to a process by its launcher or operating system.
Grouping settings in one object also makes their use visible in code review. A name such as APP_PORT shows which application owns the value, while a generic name such as PORT can collide with another tool launched in the same environment.
Reading values belongs near the startup code that builds the application’s settings. I keep file-based configuration available for nested data and environment values for simple deployment-specific inputs.
A terminal command, IDE, test runner or service manager can each provide a different configuration to the same script.
Environment values are text even when they look like numbers or flags. Use a default only when the setting is optional.
How to Read and Load Environment Variables in Python
Python provides the os mapping for values already present in the process. Use python-dotenv when local development needs a file-backed source.
Step 1: Read a required or optional value
Bracket access raises KeyError when a key is absent. getenv returns a fallback or None, letting code handle optional settings without exception handling.
Step 2: Set values for this Python process
Assign to os.environ when a Python process needs to configure a library or a child program. Set persistent values in the shell, service manager or deployment configuration that starts the program.
os.environ["APP_MODE"] = "development"
os.environ["APP_PORT"] = "8000"
Step 3: Convert and validate values
Convert a numeric string with int or float and handle malformed input with a clear startup error. For booleans, define the accepted words instead of relying on bool(value), since bool(“false”) is True because the string is non-empty.
import os
port_text = os.getenv("APP_PORT", "8000")
try:
port = int(port_text)
except ValueError as exc:
raise ValueError("APP_PORT must be an integer") from exc
raw_debug = os.getenv("APP_DEBUG", "false").strip().lower()
if raw_debug not in {"true", "false", "1", "0", "yes", "no"}:
raise ValueError("APP_DEBUG must be true/false, 1/0, or yes/no")
debug = raw_debug in {"true", "1", "yes"}
A web server can reject a port outside the range its runtime accepts before it binds a socket.
After conversion, check the allowed range too. A TCP port must fall between 1 and 65535 before it reaches a server library.
Reject an empty string when a non-empty token is required.
Step 4: Load a local .env file with python-dotenv
By default, load_dotenv searches for a .env file starting from the script context and moving up parent directories. A project can pass a specific path when it stores local settings elsewhere. This keeps the file location explicit in tools or tests that run from a different working directory.
APP_MODE=development
APP_PORT=8000
from dotenv import load_dotenv
import os
load_dotenv()
mode = os.getenv("APP_MODE", "production")
The project documentation supports expansion of braced references such as ${DOMAIN} within .env values. Bare $DOMAIN remains literal, so use braces when one value refers to another.
A deployment-provided value normally wins over a local .env value because load_dotenv does not override by default. Setting override=True reverses that precedence and can hide a deployment mistake, so use it only when the development workflow calls for it.
Use a local .env file for developer-specific settings, but configure production through its process launcher. The application can use the same os.getenv calls in both places.
For Python import basics, see Python Modules: Create and Import Them. An API client configuration example is also covered in the OpenAI Python SDK guide.
To reproduce the captured output, save this complete program as env_config_demo.py and run python3 env_config_demo.py. The code shown here is the file I ran.
import os
os.environ["APP_MODE"] = "development"
os.environ["APP_PORT"] = "8000"
mode = os.getenv("APP_MODE", "production")
port = int(os.getenv("APP_PORT", "8000"))
print(f"mode={mode}")
print(f"port={port}")
print(f"missing={os.getenv('OPTIONAL_SETTING', 'not set')}")
The exact output from my run of python3 env_config_demo.py was:
mode=development
port=8000
missing=not set

The output confirms that the process sees the values assigned in the script and that getenv returns the provided fallback for an absent optional setting. The screenshot shows the same execution and the command that produced it.
Environment Variable Mistakes and Deployment Boundaries
Use the table to locate whether the issue comes from a malformed value, a child process or a container configuration layer.
| Case | What happens | Safer approach |
|---|---|---|
| Numeric setting contains letters | int or float conversion raises ValueError. | Catch the error and give a configuration-specific message. |
| Python changes os.environ | Only that process and children started afterward see the changed value. | Set persistent values in the shell, service manager or deployment configuration. |
| Child process needs a different environment | subprocess inherits the parent’s environment unless env is supplied. | Pass a deliberate mapping to subprocess.run when the child needs a restricted or customized set. |
| Compose .env is mistaken for container input | Compose uses a project .env file for interpolation. A container needs values passed through environment or env_file. | Check the Compose documentation and declare the container environment explicitly. |
| Secret is placed in a .env file | The file can be committed or exposed if repository rules are missing. | Ignore local secret files, avoid logging values, and use deployment secret facilities where available. |
A missing setting and a malformed setting need different responses. A missing optional value can use a documented default, while a malformed required value should stop startup. Avoid silently replacing a bad number with a default because that can leave the program running with a configuration the operator did not intend.
When a setting contains a list, choose a separator and trim each item after splitting. For example, a comma-separated ALLOWED_HOSTS value can become a list with item.strip() for item in value.split(“,”) if item.strip(). Validate each entry against the format your application accepts, especially when the list controls access.
Keep configuration names consistent across local development, tests and deployment. A typo in a key usually looks like a missing value, so report the expected name in the error message. Do not include the value itself when the setting may contain a credential or private endpoint.
Changing os.environ during a running process affects subsequent reads in that process, but it does not reconfigure a library that already copied the value into its own settings object. Read configuration once at a clear startup boundary, then pass the validated settings object to the components that need it. This makes precedence and validation visible.
Do not dump the full environment when debugging. It can contain passwords, access tokens and service URLs. Print a boolean that says whether a key exists, and redact values before sending logs to a shared system.
A .env file uses dotenv syntax rather than being a Python file. Put one assignment on each line, quote values that contain characters the parser treats specially, and avoid adding Python expressions. The file is input to the loader, so a valid Python statement does not automatically make a valid dotenv entry.
Keep a .env.example file with variable names and safe placeholders. Developers can copy it to .env and add local settings, while the shared template documents required names without containing credentials.
When two configuration sources define the same key, decide which source should win and document that order. python-dotenv leaves an existing process value intact by default, so a shell or deployment value can take precedence over the local file. This is useful when the same code runs in both places, provided developers know which value they are reading.
For a required setting, report its name without printing its value. Check whether os.environ.get(“DATABASE_URL”) is empty and raise RuntimeError(“DATABASE_URL is required”) when it is.
A module-level assignment such as API_URL = os.getenv(“API_URL”) runs during import. Set the test value before importing the module, or move the read into a function the test calls. This keeps test order from changing the result.
Environment variable names are conventionally uppercase with underscores. On Windows Python normalizes keys to uppercase, while lookup is case-sensitive on many other platforms, so consistent spelling keeps settings portable across development and deployment.
A newly spawned child inherits its parent’s current environment by default. subprocess.run accepts an env mapping when the child needs an explicit set. Build that mapping from os.environ.copy() when preserving other settings matters, then change only the entries needed by the child.
A test should control the inputs it depends on instead of reading whichever values happen to be set on the developer’s machine. Pytest’s monkeypatch.setenv and monkeypatch.delenv change a test’s process environment and restore it afterward. Use a function for configuration reads when tests need to vary the value between cases.
Docker Compose adds a separate configuration layer. Its project .env file supports interpolation in the Compose file, while environment and env_file configure values inside a service container. Values explicitly assigned through environment can take precedence over values loaded from an env_file, so compare the service configuration as well as the project-level file.
Check which layer a value belongs to before debugging Python code. If Python reads None inside a container, confirm that the key is passed to that service, not only defined in a project .env file used by Compose itself.
Keep local credentials out of Git and application logs. Add the secret-bearing file to .gitignore before placing values in it, and share a separate template containing only variable names and placeholders. Environment variables reduce the chance of committing credentials in source, but they do not decide who can inspect a process or deployment configuration.
Conclusion: Keep Configuration at the Process Boundary
Document which environment supplies each setting and how developers can reproduce that setup locally. A short configuration reference prevents a guessed default from becoming an undocumented requirement.
For the precise mapping behavior, read the Python os documentation. For local .env loading, see the python-dotenv project guide, and for container configuration read Docker Compose environment variables.
FAQ
These quick answers cover common configuration choices that are distinct from the steps above.
How do I check whether an environment variable exists?
Use “NAME” in os.environ to test whether it is present. Use os.getenv(“NAME”) when you want None for a missing value.
Does os.environ change the parent shell?
No. Assignment changes the current Python process environment and can affect child processes started afterward, but it does not rewrite the parent shell’s settings.
Should python-dotenv override existing values?
By default load_dotenv leaves existing environment values in place. Set override=True only when the .env file should replace those values.


