Lesson · File I/O & Filesystem
Application Configuration & Environment Variables
64 min readApplication Configuration & Environment Variables
Configuration should be separated from source code. Environment variables are useful at process boundaries, but programs still need parsing, validation, defaults, and a clear distinction between configuration and secrets.
Learning goals
- Read a variable with
os.environ["NAME"]versusos.getenv("NAME", default)and explain when each fails. - Explain why every environment value arrives as a
strand what conversion and validation it needs before domain code sees it. - Order configuration sources by precedence and say which wins when the same setting appears twice.
- Keep secrets out of source code by loading them from the environment and separating them from ordinary settings.
- Predict what
read_config()returns whenAPP_PORTis set, unset, or malformed.
Mental model
Configuration is data that changes between deployments but not between code paths: the environment is one provider, defaults are another, and the program merges them in a fixed precedence. Values cross the process boundary as strings, so each setting needs three steps before use: fetch, convert to the right type, and validate at the boundary. Keeping those steps in one place is what makes configuration testable without editing the environment.
Core idea
A program's configuration should be read once, at the boundary, where it can be converted and validated before any deeper code assumes a shape. os.environ and os.getenv are only the lookup mechanisms; the design work is deciding which settings are required versus defaulted, what happens when a value is missing or malformed, and which values are secrets that must never enter the repository.
Process environment
The process environment is a set of name-value string pairs inherited when a program starts (from a shell, a service manager, or a container runtime) and readable at any time through os.environ or os.getenv. Child processes inherit a copy, changes made after launch are not seen by processes already running, and names are case-sensitive on POSIX systems while Windows treats them case-insensitively.
os.environ
os.environ is a mutable mapping view of the process environment. Read configuration near the application boundary and convert strings into validated domain values before deeper code uses them.
os.getenv()
os.getenv('NAME') returns the variable's string value or None when it is missing; with a second argument it returns that default instead. It never raises for a missing name, unlike os.environ['NAME'], which raises KeyError, but it also performs no conversion, so "8000" comes back as a string that must be turned into an int before arithmetic.
Required vs optional configuration
Required settings have no sensible fallback: when they are missing, the program should fail fast with an error that names the variable, not with a None that flows into the code. Optional settings carry a documented default so the program runs without them; deciding which is which is a design choice that belongs next to the code that reads them.
Defaults
A default is the value used when the environment provides nothing, and it should be a valid, safe value rather than a placeholder that hides misconfiguration. os.getenv('APP_PORT', '8000') supplies the string default at lookup time; giving a truly required setting a default is often the wrong move, because a typo then goes unnoticed.
Configuration validation
Configuration validation should happen at a boundary where invalid data can be rejected with a useful error. Keep validation rules explicit and avoid silently converting values in ways that hide mistakes.
Secrets vs ordinary configuration
Ordinary configuration can be logged, committed in example form, and shared across environments; secrets (passwords, tokens, keys) must come from the runtime environment or a secret manager and must never be written to source, logs, or error messages. Both arrive as strings, so the distinction is operational rather than technical: only one of them is safe for other people to read.
Avoiding credentials in source code
Credentials in source are copied into version history, build artifacts, and screenshots, where deleting them later does not undo the exposure. The standard practice is to read secrets from environment variables at runtime, keep local values in a file that version control ignores (with a committed example showing the variable names), and rotate anything that was ever committed.
Configuration precedence
When several sources can supply the same setting, precedence is the fixed order in which they are consulted, commonly command-line arguments, then environment variables, then a config file, then built-in defaults. Write the order down and implement it in one merge function; lookups scattered through the codebase make the effective value depend on call order.
Twelve-factor-style environment configuration as a common application pattern
The twelve-factor style treats configuration that varies between deployments as environment variables, so the same built artifact runs everywhere and nothing environment-specific is baked in. The practical test: if moving from staging to production requires editing files inside the application directory, configuration is still coupled to the build.
Walkthrough
os.getenv("APP_PORT", "8000")returns a string whether the variable is set or the default is used, soraw_portis alwaysstr;int(raw_port)performs the conversion, and invalid digits raiseValueError.- The
try/exceptre-raises aValueErrorthat namesAPP_PORTand chains the original withfrom exc, so the operator sees which setting is wrong instead of a bareinvalid literal for int()message. os.getenv("APP_DEBUG", "")defaults to an empty string;.lower() in {"1", "true", "yes"}accepts the common spellings of on, and any other value, including empty, meansFalse.- Predict before running: the returned dict when nothing is set, when
APP_PORT=abc, and whenAPP_DEBUG=yes.
Experiments to try
- Run the snippet as-is, then run it with
APP_PORT=9000set in the shell; print the result both times and name the lookup that explains the change. - Set
APP_PORT=8080.0and read the chained exception; decide whether a port should accept floats and how the error message would change if it did. - Add
os.getenv("APP_DEBUG")without a default and compare theNonehandling with the current empty-string default; note which is clearer. - Print
sorted(os.environ)and find one inherited variable such asPATH; explain why printing variable names is safe when printing all values may not be.
Common mistakes
- Reading
os.environ["APP_PORT"]for a variable that may be absent: the missing name raisesKeyErrordeep in the program instead of failing clearly at startup. - Trusting a naive boolean conversion:
os.getenv("APP_DEBUG")returns the string"false"too, andbool("false")isTrue, so the intended meaning inverts. - Writing a real secret into a config file or source default while developing and shipping it: the value persists in version history and build artifacts after the file is cleaned up.
- Scattering lookups through the codebase: the same setting is read with different defaults in different modules, so the effective configuration depends on which path runs first.
Practice: Easy
- Write
port()returningint(os.getenv("APP_PORT", "8000"))and run it with the variable set, unset, and set to"port"; record the three outcomes. - Print
os.getenv("APP_MISSING")and compare it withos.environ.get("APP_MISSING", "fallback"); explain theNoneversus default difference. - Convert
"false","FALSE", and"0"to booleans with a small helper and check it agrees with theread_configrule for debug flags.
Practice: Medium
- Extend
read_configwith aMODEsetting restricted to"dev"and"prod"; invalid values must raiseValueErrornaming the variable and the allowed choices. Test all three branches. - Build
load(overrides)that merges built-in defaults, environment values, and an explicit override dict in a stated precedence; test that each source wins over the one before it. - Refactor a script that hardcodes a path and a threshold into one that reads both from the environment with defaults, and list which values you would make required instead.
Practice: Hard
- Design a startup configuration step for a small service: fetch each setting once, convert and validate it, and fail with one combined message listing every invalid or missing required variable. Define the return type and its invariants.
- Write a test that proves a secret never leaks: set a dummy value, run a failing configuration path, and assert the value does not appear in the exception text or logs.
- Compare two precedence orders on paper (environment over file, file over environment) and describe one deployment where each order causes a surprising result; recommend one order and justify it.
Lesson checklist
- I can explain why every environment value needs conversion and validation before use.
- I can pick between
os.environ[...],os.getenv(...), and a default for a given setting. - I can state a precedence order and point to the one function that implements it.
- I can keep a secret out of source, logs, and error messages while still failing usefully when it is missing.
Remember
Configuration is a boundary concern: values arrive as strings from the environment, so the program should fetch, convert, and validate them in one place before deeper code assumes anything. Choose required versus optional settings deliberately, give optional ones real defaults, and keep secrets out of the repository; `os.environ`, `os.getenv`, and a documented precedence order are the mechanisms for that single design.
Interview angles
What is the main purpose of **Process environment**?+
The process environment is the set of name-value string pairs inherited when a program starts; os.environ exposes it as a mapping, and child processes inherit a copy. Values arrive as strings, so conversion and validation stay the program's job.
What should you pay attention to when using **os.environ**?+
os.environ is a mutable mapping view of the process environment. Read configuration near the application boundary and convert strings into validated domain values before deeper code uses them.
How does **os.getenv()** fit into this lesson?+
os.getenv is the forgiving lookup: it returns None (or a supplied default) for a missing name instead of raising KeyError, and it performs no conversion. The worked example uses it to fetch APP_PORT as a string and then validates the conversion explicitly.
Why does a helper like `bool(os.getenv("APP_DEBUG"))` misread `APP_DEBUG=false`?+
Any non-empty string is truthy in Python, so "false" converts to True; compare the lowercased value against an explicit set of accepted spellings, as read_config does.