Skip to main content
Environment variables are named values stored at the operating system level, completely outside your application code. When your Python program runs, it can ask the OS for those values at any time — but the values themselves never appear in your source files. This separation is what makes them the right place to store anything that’s sensitive (like API keys), machine-specific (like a database URL that differs on each developer’s laptop), or likely to change between environments (like whether debug mode is on or off).

The problem they solve

This pattern creates three problems:
  • Secrets are visible in your code and Git history
  • You can’t safely share your code with others
  • Different machines need different settings but require code changes

How environment variables work

Environment variables live in your operating system, not in your code:

Setting them in the terminal

You can set environment variables temporarily from the terminal:
The variable is available while that terminal session is open. Close the terminal and it’s gone — which is why .env files (covered on the next page) are a better approach for persistent configuration.

Reading environment variables in Python

Method 1 (.get() with a default) is the most common in practice. Method 3 is useful when a missing variable should be treated as an unrecoverable error, such as when starting a server without its required credentials.

Common uses

  • API keysOPENAI_API_KEY, GITHUB_TOKEN, STRIPE_SECRET_KEY
  • Database URLsDATABASE_URL, REDIS_URL
  • App settingsDEBUG=True, PORT=8000, LOG_LEVEL=INFO
  • File pathsLOG_DIR, UPLOAD_FOLDER

Important rules

  • Environment variables are always strings — if you need a number or boolean, convert them explicitly (int(os.environ.get("PORT", "8000")))
  • Names are UPPERCASE by convention
  • Values are machine-specific — your DATABASE_URL will be different from a teammate’s
  • They don’t persist between terminal sessions unless you set them in a shell profile or use a .env file

What’s next?

Setting variables by hand every session is tedious. .env files give you a much cleaner workflow.

Using .env files

The easier way to manage environment variables