Python Environment Variables: export, env, printenv & .env Loading
Environment variables are globally accessible key-value pairs inherited by child processes. The `export` command promotes a local shell variable into the environment table. Loading `.env` files safely without executing arbitrary code is a staple of production deployment.
"A regular variable is a note on your personal desk; an `export` variable is a company-wide memo broadcast to every worker and contractor in the building."
Deep Dive: How It Works
export Mechanism: Without `export`, variables remain private to the current shell process; `export VAR="val"` copies them to all child subprocesses.
Inspecting Environment: `printenv` or `env` lists all exported variables.
Safe `.env` Loading: `set -a; source .env; set +a` automatically exports all declared variables in the dotenv file.
Syntax Blueprint
export DATABASE_URL="postgres://user:pass@host:5432/db" export PORT=8080 # Safe .env loader in scripts: if [[ -f ".env" ]]; then set -a source .env set +a fi
Use export for child inheritance and set -a to auto-export sourced .env keys.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Setting `API_KEY="secret"` in bash and wondering why a Python script `os.getenv("API_KEY")` returns None.Why it happens: Without `export`, the variable is local to the shell and not passed to child processes.
How to fix: Write `export API_KEY="secret"`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Export and Print an Environment Variable
Export `export PLATFORM="ZenCompiler"`.
Print it from a child subshell using `bash -c 'echo "Platform: $PLATFORM"'`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.