Configuration such as API keys, ports and feature flags is usually passed to programs through environment variables.
os.environ is a dict-like mapping of the process's environment variables, captured when Python starts. Keys and values are always strings.
os.environ["HOME"]raisesKeyErrorif the variable is missing.os.environ.get("PORT", "8000")oros.getenv("PORT", "8000")return a default instead.- Assigning
os.environ["MODE"] = "test"updates the mapping and the real process environment, so child processes started afterwards (withsubprocess) inherit it. del os.environ["MODE"]oros.environ.pop("MODE", None)removes it.
Because values are strings, convert explicitly: int(os.environ.get("WORKERS", "4")). Booleans need care: bool("0") is True, so compare against accepted spellings like {"1", "true", "yes"}.
Changes only affect the current process and its future children. A Python program can never change the environment of the shell that started it.
On Windows, keys are case-insensitive (PATH and Path are the same variable). On POSIX they are case-sensitive.
Prefer os.environ over the low-level os.putenv/os.unsetenv: those change the real environment but do not update os.environ, so later reads disagree.
Example
import os
import subprocess
import sys
print(os.environ.get("APP_MODE", "dev")) # dev
os.environ["APP_MODE"] = "test"
print(os.getenv("APP_MODE")) # test
# children inherit the modified environment
code = "import os; print(os.environ['APP_MODE'])"
out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
print(out.stdout.strip()) # test
workers = int(os.environ.get("WORKERS", "4"))
debug = os.environ.get("DEBUG", "0").lower() in {"1", "true", "yes"}
print(workers, debug) # 4 False
del os.environ["APP_MODE"]
print("APP_MODE" in os.environ) # FalseRemember
os.environis a str-to-str mapping; use.getwith a default for optional settings- Assigning to
os.environaffects this process and children started later - Convert values yourself;
bool('0')is True
Watch out for
- Expecting a script to change the parent shell's environment; that is impossible from a child process.