Environment variables

os · Essentials · 8 min

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"] raises KeyError if the variable is missing.
  • os.environ.get("PORT", "8000") or os.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 (with subprocess) inherit it.
  • del os.environ["MODE"] or os.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)            # False

Remember

  • os.environ is a str-to-str mapping; use .get with a default for optional settings
  • Assigning to os.environ affects 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.

Check yourself

  1. A program runs os.environ['TOKEN'] = 'abc' and exits. What does the shell that launched it see in $TOKEN afterwards?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/os.html#os.environ