Python Basics: Reading and Validating Environment Variables
Environment variables let a Python script accept small settings without editing its source. Python’s standard-library os module reads them as strings.
Use Python 3.12 or newer in Bash on Linux. The examples use invented settings and change only a child process’s environment. Never print the whole environment: it can contain credentials.
Read a value and a default
An assignment before a command supplies a variable to that command. env -u removes the named variable from that command’s environment so the default is reproducible.
Save as demo_environment_variables_1.py:
import os
print(os.environ["DEMO_WORKERS"])
print(os.getenv("DEMO_REGION", "local"))
print(type(os.environ["DEMO_WORKERS"]).__name__)Run:
env -u DEMO_REGION DEMO_WORKERS=3 python3 demo_environment_variables_1.pyOutput:
3
local
stros.environ["NAME"] raises KeyError when a required setting is missing. os.getenv("NAME", default) returns the default only when the setting is absent. An empty value is still present.
Convert and validate numbers
Convert strings explicitly, then check the range your program supports. This example accepts one to eight workers.
Save as demo_environment_variables_2.py:
import os
def worker_count(raw):
try:
value = int(raw)
except ValueError:
raise ValueError("DEMO_WORKERS must be an integer") from None
if not 1 <= value <= 8:
raise ValueError("DEMO_WORKERS must be between 1 and 8")
return value
print("Workers:", worker_count(os.getenv("DEMO_WORKERS", "2")))
for raw in ("many", "0", ""):
try:
worker_count(raw)
except ValueError as error:
print(error)Run:
DEMO_WORKERS=3 python3 demo_environment_variables_2.pyOutput:
Workers: 3
DEMO_WORKERS must be an integer
DEMO_WORKERS must be between 1 and 8
DEMO_WORKERS must be an integerFor an actual application, handle invalid configuration at startup and stop rather than silently using an unintended value. Avoid including secret values in error messages.
Don’t use bool() to parse a flag
Any nonempty string is truthy, including "false". Define the accepted spelling instead.
Save as demo_environment_variables_3.py:
import os
raw = os.getenv("DEMO_DEBUG", "false").strip().lower()
if raw not in {"true", "false"}:
raise SystemExit("DEMO_DEBUG must be true or false")
print("Debug:", raw == "true")Run:
DEMO_DEBUG=false python3 demo_environment_variables_3.pyOutput:
Debug: FalseReferences
Acknowledgements
This post was created with assistance from AI.