Read environment variables in Python

Read required and optional environment variables, convert configuration values, and load a .env file during local development.

Best practices
Read environment variables in Python illustration

Use os.environ['NAME'] for a required variable and os.getenv('NAME', default) for an optional one. Missing required configuration should often fail early, rather than silently fall back to an unsuitable value.

import os

db_host = os.environ['DB_HOST']          # Raises KeyError if absent
db_port = os.getenv('DB_PORT', '5432')   # Default only when absent
debug_text = os.getenv('DEBUG')         # None if absent

os.environ.get() offers the same lookup style as os.getenv(). An existing variable whose value is '' does not trigger the default.

Check, convert, set, and remove values

if 'API_KEY' in os.environ:
    pass  # Present; this does not prove it is nonempty or valid

workers = int(os.getenv('WORKERS', '4'))
debug = os.getenv('DEBUG', '').strip().lower() in {'1', 'true', 'yes'}

os.environ['MY_VAR'] = 'value'
os.environ.pop('MY_VAR', None)

Values read through os.environ are strings. Validate conversions and allowed ranges: int() raises ValueError for malformed input, while this simple Boolean parser treats unknown values as false. Use stricter validation when a misspelled setting must be rejected.

Load .env values for local development

python -m pip install python-dotenv
from dotenv import load_dotenv

load_dotenv()

python-dotenv reads a .env file into the process environment. By default it preserves already-set variables. Keep secret-bearing files out of source control and avoid dumping the environment into logs.

FAQ

Why does a running process not see my shell change?

A child process inherits an environment when it starts. Changing a parent shell afterward does not update the child’s configuration. Restart with the new environment, or implement an explicit configuration reload path. Assigning to os.environ affects this process and subsequently launched children, not the parent shell.

Are environment variables a secure place for secrets?

They avoid hard-coding secrets into source, but remain accessible to the process and can leak through diagnostics or process inspection. Use your deployment platform’s secret injection and access controls; for Kubernetes, configure Secret access and encryption appropriately rather than treating environment variables themselves as encryption.

See Python operating-system interfaces, python-dotenv documentation.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting