Question

How to Access Environment Variables in Python

pythonenvironment-variables

Question

How can I get the value of an environment variable in Python?

Short Answer

By the end of this page, you will understand how Python reads environment variables, how to safely access them with os.environ and os.getenv, what happens when a variable is missing, and how this is commonly used in real applications for configuration, secrets, and deployment settings.

Concept

Environment variables are key-value pairs provided by the operating system to a running program. In Python, they are commonly used to pass configuration into an application without hardcoding values directly in the source code.

This matters because real programs often need values that change between environments, such as:

  • database URLs
  • API keys
  • debug flags
  • file paths
  • port numbers

Python provides access to environment variables through the os module.

Two common ways to read them are:

  • os.environ["NAME"]
  • os.getenv("NAME")

They look similar, but they behave differently when the variable does not exist:

  • os.environ["NAME"] raises a KeyError
  • os.getenv("NAME") returns None by default, or a fallback value if you provide one

Using environment variables helps keep code portable and secure. For example, you should usually store secrets like API tokens in environment variables instead of committing them into your codebase.

Mental Model

Think of environment variables like labeled sticky notes attached to your program when it starts.

Each sticky note has:

  • a name, such as DATABASE_URL
  • a value, such as postgres://localhost:5432/app

Your Python program can read those notes while it runs.

  • os.environ["DATABASE_URL"] means: "Give me the note with this exact name, and fail if it is missing."
  • os.getenv("DATABASE_URL") means: "Give me the note if it exists, otherwise give me nothing or a default value."

This is useful because the same program can behave differently depending on which notes the operating system provides.

Take Quiz

Syntax and Examples

The os module gives access to environment variables.

Basic syntax

import os

value = os.environ["VARIABLE_NAME"]
import os

value = os.getenv("VARIABLE_NAME")
import os

value = os.getenv("VARIABLE_NAME", "default_value")

Example: read an environment variable

import os

username = os.getenv("USERNAME")
print(username)

This tries to read the USERNAME environment variable.

  • If it exists, its value is returned.
  • If it does not exist, None is returned.

Example: provide a default value

import os

mode = os.getenv("APP_MODE", "development")
print(mode)

If APP_MODE is not set, Python uses "development".

Example: require a variable

import os

api_key = os.environ["API_KEY"]
print(api_key)

This is useful when the variable must exist. If API_KEY is missing, Python raises a KeyError.

Example: safer handling for required values

import os

api_key = os.getenv("API_KEY")

if api_key is None:
    raise ValueError("API_KEY is required")

print(api_key)

This gives you more control over the error message.

Step by Step Execution

Consider this example:

import os

port = os.getenv("PORT", "8000")
print(port)

Step by step

  1. Python imports the os module.
  2. os.getenv("PORT", "8000") checks whether the environment contains a variable named PORT.
  3. If PORT exists, its value is returned.
  4. If PORT does not exist, the default value "8000" is returned.
  5. The result is stored in port.
  6. print(port) outputs the final value.

Example outcomes

If the environment contains:

PORT=5000

then the output is:

5000

If PORT is not set, the output is:

8000

Important detail

Environment variable values are strings. Even if PORT looks like a number, Python reads it as text.

import os

port = int(os.getenv("PORT", "8000"))
print(port + 1)

Here, int(...) converts the string into an integer so it can be used numerically.

Real World Use Cases

Environment variables are widely used in real software.

Application configuration

import os

debug = os.getenv("DEBUG", "false")

A web app may enable or disable debug mode based on deployment settings.

Database connections

import os

database_url = os.getenv("DATABASE_URL")

Applications often read connection strings this way so development, staging, and production can use different databases.

API credentials

import os

api_token = os.getenv("API_TOKEN")

Secrets should usually come from the environment instead of being hardcoded.

Server port selection

import os

port = int(os.getenv("PORT", "8000"))

Platforms like cloud hosting services often provide the port through an environment variable.

File and path settings

import os

log_dir = os.getenv("LOG_DIR", "/tmp/logs")

Scripts can adapt to different machines without changing the code.

Take Quiz

Real Codebase Usage

In real projects, developers rarely read environment variables randomly throughout the codebase. Instead, they usually centralize configuration.

Common pattern: configuration section

import os

class Config:
    DEBUG = os.getenv("DEBUG", "false").lower() == "true"
    PORT = int(os.getenv("PORT", "8000"))
    DATABASE_URL = os.getenv("DATABASE_URL")

This keeps configuration in one place.

Guard clause for required settings

import os

database_url = os.getenv("DATABASE_URL")
if not database_url:
    raise RuntimeError("DATABASE_URL is required")

This fails early instead of causing confusing errors later.

Validation and conversion

import os

raw_timeout = os.getenv("TIMEOUT", "30")
timeout = int(raw_timeout)

Since environment variables are strings, developers often convert them into int, float, or bool.

Sensible defaults

import os

log_level = os.getenv("LOG_LEVEL", "INFO")

Defaults make local development easier while still allowing overrides.

Avoiding repeated lookups

Instead of calling os.getenv("PORT") in many files, teams usually read the variable once and pass the value into the parts of the application that need it.

This makes testing easier and reduces hidden dependencies.

Common Mistakes

1. Forgetting to import os

Broken code:

value = os.getenv("HOME")

Problem:

  • os is not defined.

Fix:

import os

value = os.getenv("HOME")

2. Using os.environ[...] when the variable might be missing

Broken code:

import os

mode = os.environ["APP_MODE"]

Problem:

  • This raises KeyError if APP_MODE is not set.

Fix:

import os

mode = os.getenv("APP_MODE", "development")

3. Forgetting that values are strings

Broken code:

import os

port = os.getenv("PORT", 8000)
print(port + 1)

Problem:

  • If PORT exists, it will be a string like "8000", and adding 1 will fail.

Fix:

import os

port = int(os.getenv("PORT", "8000"))
print(port + 1)

4. Assuming booleans are automatic

Broken code:

import os

debug = bool(os.getenv("DEBUG"))
print(debug)

Problem:

  • bool("false") is True because any non-empty string is truthy.

Fix:

import os

debug = os.getenv("DEBUG", "false").lower() == "true"
print(debug)

5. Hardcoding secrets in source code

Broken code:

API_KEY = "my-secret-key"

Problem:

  • Secrets can leak into version control.

Fix:

import os

API_KEY = os.getenv("API_KEY")

6. Not handling missing required variables clearly

Broken code:

import os

send_to_service(os.getenv("SERVICE_URL"))

Problem:

  • If SERVICE_URL is missing, the failure may happen later and be harder to debug.

Fix:

import os

service_url = os.getenv("SERVICE_URL")
if service_url is None:
    raise ValueError("SERVICE_URL is required")

send_to_service(service_url)

Comparisons

ApproachMissing variable behaviorBest use caseExample
os.environ["NAME"]Raises KeyErrorRequired variablesos.environ["API_KEY"]
os.getenv("NAME")Returns NoneOptional variablesos.getenv("LOG_LEVEL")
os.getenv("NAME", "default")Returns default valueOptional variables with fallbackos.getenv("PORT", "8000")

os.environ vs os.getenv

  • Use os.environ[...] when the variable must exist and you want failure immediately.
  • Use os.getenv(...) when the variable is optional or you want to provide a fallback.

Required vs optional configuration

TypeTypical handling
RequiredRead it and raise a clear error if missing
OptionalUse os.getenv() with a sensible default

Hardcoded values vs environment variables

ApproachAdvantageDrawback
Hardcoded valueSimple for quick testsHard to change across environments
Environment variableFlexible and safer for configMust be set correctly in the environment
Take Quiz

Cheat Sheet

import os

Read a required variable

value = os.environ["NAME"]
  • Raises KeyError if missing

Read an optional variable

value = os.getenv("NAME")
  • Returns None if missing

Read with a default

value = os.getenv("NAME", "default")

Convert to integer

port = int(os.getenv("PORT", "8000"))

Convert to boolean safely

debug = os.getenv("DEBUG", "false").lower() == "true"

Check for required variable manually

api_key = os.getenv("API_KEY")
if api_key is None:
    raise ValueError("API_KEY is required")

Key rules

  • Environment variable names are strings.
  • Environment variable values are also strings.
  • Missing variables should be handled intentionally.
  • Use environment variables for configuration and secrets.
  • Avoid hardcoding sensitive values in code.

FAQ

How do I read an environment variable in Python?

Use the os module:

import os
value = os.getenv("MY_VAR")

What is the difference between os.getenv() and os.environ[]?

os.getenv() returns None or a default value if the variable is missing. os.environ[] raises KeyError if it is missing.

How do I provide a default value for an environment variable in Python?

Pass a second argument to os.getenv():

port = os.getenv("PORT", "8000")

Why is my environment variable a string even when it looks like a number?

Environment variables are stored as text. Convert them explicitly:

timeout = int(os.getenv("TIMEOUT", "30"))

How do I check if an environment variable exists in Python?

You can use either:

import os

exists = os.getenv("MY_VAR") is not None

or:

import os

exists = "MY_VAR" in os.environ

Should I store API keys in environment variables?

Yes, that is a common and safer practice than hardcoding them in source code.

Can I change environment variables from Python?

Yes, you can assign values in os.environ, but that change only affects the current process and child processes started from it.

Take Quiz

Mini Project

Description

Build a small Python configuration loader for a script. This project demonstrates how to read required and optional environment variables, apply defaults, and convert string values into useful Python types.

Goal

Create a Python script that loads app settings from environment variables and prints the final configuration safely.

Requirements

Requirement 1 Requirement 2 Requirement 3

Take Quiz

Keep learning

Related questions

View more