Every application needs configuration. Database URLs, API keys, secret tokens, and debug flags all change depending on the environment your code runs in. Hardcoding them into your source files is a bad idea. Anyone who reads your code or your Git history can see them. That is where environment variables in Python come in.
Environment variables are key-value pairs that your operating system stores outside your code. Your Python program can read them at runtime. This keeps sensitive data out of your source files and makes your application flexible across different environments like development, staging and production.
In this article, you will learn what environment variables are, how Python handles them, how to read and set them, which built-in Python environment variables matter most, and how to manage them cleanly using a .env file.
Related Article: How To Learn Python?
An environment variable is a named value that lives in your system's environment. Your shell, operating system, and running processes all have access to them.
You can think of them as global settings for your system. When you run a Python script, the script inherits all the environment variables that are active in the current session.
For example, on Linux or macOS, you can set an environment variable directly in the terminal:
| export DATABASE_URL="postgresql://user:password@localhost/mydb" |
On Windows (Command Prompt):
| set DATABASE_URL=postgresql://user:password@localhost/mydb |
Your Python code can then read this value without you ever writing the actual URL inside the script.
Python gives you access to environment variables through the built-in os module. You don’t have to install anything. Just import it.
| import os |
The os module provides os.environ, which is a dictionary-like object. It contains all the environment variables available to the current process. You can read from it, write to it, and delete from it just like a regular Python dictionary.
The most direct way to read an environment variable is to access os.environ like a dictionary.
|
import os db_url = os.environ["DATABASE_URL"] print(db_url) |
This approach works well when you are sure the variable exists. But if it does not, Python raises a KeyError. That can crash your program unexpectedly.
The os.getenv() function is the safer approach. It returns None by default if the variable does not exist. You can also specify your own default value.
|
import os db_url = os.getenv("DATABASE_URL", "postgresql://localhost/default_db") print(db_url) |
This is the recommended way to read environment variables in Python. It prevents crashes and lets you define fallback values for local development.
You can view every environment variable in the current session by printing os.environ.
|
import os for key, value in os.environ.items(): print(f"{key} = {value}") |
This is useful during debugging to confirm that your variables are loaded correctly.
Also Read: Python Libraries for Machine Learning
You can set environment variables directly in Python by assigning to os.environ.
|
import os os.environ["APP_MODE"] = "production" print(os.environ["APP_MODE"]) # Output: production |
Keep one important thing in mind. When you set an environment variable this way, it only exists for the lifetime of that process. It does not persist after the script finishes. It also does not affect your system-level environment.
If you want a variable to persist across sessions, you need to set it at the shell level or in a configuration file.
You can remove an environment variable using either os.environ.pop() or del.
|
import os os.environ["TEMP_KEY"] = "temporary" # Remove it using pop (safe — no error if key is missing) os.environ.pop("TEMP_KEY", None) # Or remove it using del (raises KeyError if missing) del os.environ["TEMP_KEY"] |
Use pop() when you are not sure whether the variable exists. It is the safer option.
Read Also: A Comprehensive Guide to Python Testing
Python reads certain environment variables at startup to control its own behavior. These are not custom variables you define. Python itself uses them.
PYTHONPATH tells Python where to look for modules. It adds extra directories to sys.path, which is the list Python searches when you use an import statement.
| export PYTHONPATH="/home/user/myproject/modules" |
This is useful when you have custom modules that are not installed in the standard library location.
PYTHONHOME sets the default location for Python's standard library files. Python uses this to find its core library when it starts. You will mostly use this when you embed Python in another application or when you work with a custom Python build.
When Python starts in interactive mode, it looks for a startup file. PYTHONSTARTUP holds the path to that file. Python runs the commands inside it before giving you the prompt. Developers often use this to auto-import commonly used modules in the interactive shell.
| export PYTHONSTARTUP="/home/user/.pythonrc.py" |
Setting PYTHONINSPECT forces Python into interactive mode after a script finishes running. This is the same as using the -i flag when you run a script from the command line. It is very helpful when you want to inspect variables or objects after your program exits.
|
export PYTHONINSPECT=1 python myscript.py |
PYTHONVERBOSE tells Python to print a message every time it initializes a module. It also shows where the module file is loaded from. Set this when you are debugging import issues or when you want to trace which modules your application is loading.
| export PYTHONVERBOSE=1 |
On Windows, PYTHONCASEOK makes Python ignore cases when it handles import statements. Python searches for the first case-insensitive match for the module name. This is specific to Windows and is not relevant on Linux or macOS, which have case-sensitive file systems.
Read Also: Python Basic Syntax
Manually exporting environment variables before every run can become tedious. The python-dotenv package solves this. It reads a .env file from your project root and loads the variables into os.environ automatically.
| pip install python-dotenv |
|
DATABASE_URL=postgresql://user:password@localhost/mydb SECRET_KEY=mysupersecretkey DEBUG=True |
|
from dotenv import load_dotenv import os load_dotenv() db_url = os.getenv("DATABASE_URL") secret = os.getenv("SECRET_KEY") print(db_url) print(secret) |
load_dotenv() reads the .env file and injects all the variables into os.environ. Your code then accesses them through os.getenv() as usual.
This pattern is standard in modern Python development, especially in Flask and Django projects.
Important: Always add .env to your .gitignore file. Never commit it to version control. This keeps your secrets private and allows teammates to define their own local values.
Sometimes you need to verify that a variable is set before using it. You can do this with an easy check.
|
import os if "API_KEY" in os.environ: print("API key is set.") else: print("API key is missing. Please set it before running.") |
This is a clean way to validate your environment at startup and fail early if something is missing.
Following a few good habits will save you from security issues and deployment headaches.
Store secrets outside your code: API keys, database passwords, and tokens should never appear in your source files. Use environment variables or a secrets manager.
Use os.getenv() with defaults: Always provide a fallback value for variables that are optional. This makes your code work locally without full configuration.
Validate at startup: Check for required variables when your application starts. Raise a clear error if they are missing. This is better than allowing your application to fail unexpectedly during execution.
Never commit .env files: Add them to .gitignore immediately. Use a .env.example file with placeholder values to guide your teammates.
Use separate variables per environment: Keep development, staging, and production configurations separate. Don’t share secrets across environments.
Also Read: Matplotlib Library in Python
Environment variables are one of the most important tools in Python development. They separate configuration from code, protect sensitive information, and help applications run consistently across different environments.
Python's os module gives you everything you need to read, set, and delete environment variables with just a few lines of code. Built-in Python environment variables like PYTHONPATH, PYTHONSTARTUP, and PYTHONINSPECT give you fine-grained control over how Python itself behaves. And tools like python-dotenv make managing environment variables in your project clean and effortless.