Python Env Vars: Complete Guide to Environment Variables
Python environment variables are essential for secure application development, allowing us to store sensitive data like API keys and database credentials outside our code. This comprehensive guide shows you how to set, access, and manage Python environment variables using os.environ
and .env
files with practical examples and best practices.
Let’s start by understanding what environment variables are in Python.
What are environment variables in Python?
Python environment variables are key-value pairs stored in our operating system that contain configuration data for our applications. They allow us to:
- Store sensitive information (API keys, passwords) outside our source code
- Configure application behavior without changing code
- Switch between different environments (development, production) easily
For instance, let’s say we’re building a weather app that retrieves data from an external API. Instead of hardcoding the API key like this:
API_KEY = "12345abcdef"
We can use an environment variable called WEATHER_API_KEY
to store and access the key securely:
import osAPI_KEY = os.getenv("WEATHER_API_KEY")
This not only keeps our code cleaner but also protects sensitive data from leaks.
Next, we’ll learn how to get or access environment variables in Python.
Intro to C#
Dive into C#, a scalable programming language that is easy to read and maintain. Try it for freeHow to get environment variables in Python
Python provides a straightforward and secure way to get environment variables through the built-in os
module.
Using os.getenv()
The most common method to access an environment variable in Python is with os.getenv()
. Let’s see how we can use it in our Python script:
import osapi_key = os.getenv("API_KEY")
This method attempts to retrieve the value of the environment variable named “API_KEY”. If the variable doesn’t exist, it returns None
.
We can also provide a fallback default:
debug_mode = os.getenv("DEBUG", "False")
When we set DEBUG=False
, we’re telling our Python application to:
- Disable debug mode
- Hide detailed error messages
- Avoid exposing sensitive internal information
This setting is meant for production environments — the live version of our app that real users interact with.
This approach is safe and commonly used, as the variable might not always be defined.
Using os.environ
Alternatively, Python provides os.environ
, which behaves like a dictionary and gives direct access to the environment:
import osapi_key = os.environ["API_KEY"]
This method is stricter. If “API_KEY” is not set, it raises a KeyError
. This is helpful when we want our app to fail if a required variable is missing.
Loading environment variables from a .env
file
A .env
file is not loaded automatically in a Python script. Instead, we need to use the python-dotenv
library to load it:
from dotenv import load_dotenvimport osload_dotenv() # This loads variables from .env into os.environapi_key = os.getenv("API_KEY")debug = os.getenv("DEBUG", "False")
Now, we can access the key whenever we want in our Python code.
Now that we know how to get Python env vars, let’s see how to set them efficiently.
How to set environment variables in Python
When we talk about setting environment variables in Python, we’re essentially telling our system or application to store configuration data outside of our code. This approach improves security, makes deployment smoother, and simplifies working across multiple environments.
Here are several methods to set environment variables in Python, depending on whether we’re running code locally or in a terminal.
1. Setting environment variables temporarily
We can set up a temporary environment variable using the terminal. This method works well for quick testing or temporary setups.
To do so, open the terminal and run this command:
export API_KEY="mysecret"export DEBUG="True"
When we set DEBUG="True"
, we tell the application to run in debug mode — a special mode meant for development, not production. In debug mode:
- The app provides detailed error messages when something goes wrong.
- The debugger is enabled, allowing interactive inspection of errors.
- Changes to our code are automatically reloaded without restarting the server.
This variable is now available to any Python script launched from that terminal session. However, it will disappear once we close the terminal or restart the computer. This leads us to the next topic — setting environment variables permanently.
2. Setting environment variables permanently
For more permanent setups, especially in development, we can add variables to our shell configuration file.
To do that, navigate to ~/.bashrc
and add these lines to the file:
export API_KEY="mysecret"export DEBUG="True"
Next, run this command in the terminal:
source ~/.bashrc
Now, this environment variable is permanently available in every new terminal session.
3. Using a .env
file
This is the recommended approach for most Python projects. A .env
file stores our environment variables in a simple text format:
API_KEY=your-api-keyDATABASE_URL=postgres://user:pass@localhost/dbDEBUG=True
We can create this file at the root of our project.
To make these variables accessible in our Python code, we can use the python-dotenv
library.
Let’s see how to set up a .env
file for a Python project.
Step 1: Open the terminal and execute this command to install the python-dotenv
package.
pip install python-dotenv
Step 2: Navigate to the root of our project and create a .env
file there.
touch .env
Step 3: Insert these lines into the .env
file.
API_KEY=mysecretDEBUG=True
Once the .env
file is created, we’re eligible to access the variable stored in it in our Python code.
Since we’re done discussing how to get, set, and manage Python environment variables, let’s explore some best practices for managing them efficiently.
Best practices for using environment variables in Python
To keep our project secure and maintainable, we can follow these best practices when working with environment variables in Python:
- Avoid hardcoding sensitive data: Never write credentials, tokens, or keys directly in your code.
- Use
.env
files for local development: This helps manage variables effectively and keeps them separate from your codebase. - Ignore
.env
files in version control: Always add.env
to your.gitignore
to prevent leaking secrets. - Validate required environment variables: Check at startup if critical variables are present to prevent runtime errors.
- Use environment-specific configurations: For different environments (development, staging, production), set up different sets of variables.
Following these best practices will ensure effective usage of Python environment variables.
Conclusion
Throughout this tutorial, we explored how environment variables in Python help us manage configurations securely and efficiently. By keeping sensitive data—like API keys, database credentials, and secret tokens—out of our source code, we reduce the risk of exposure and make our projects easier to maintain across environments.
If you want to expand your knowledge of Python, check out the Learn Python 3 course on Codecademy.
Frequently asked questions
1. How to list all environment variables in Python?
Use os.environ.items()
to list all Python environment variables:
import osfor key, value in os.environ.items():print(f"{key}: {value}")
2. What is the best way to load environment variables in Python?
The best way to load Python environment variables is using a .env
file with the python-dotenv
library for organized, secure configuration management.
3. When should you use Python environment variables?
Use Python environment variables to store sensitive data, manage different environment configs, and avoid hardcoding values that change across deployments.
4. Can environment variables manage multiple environments in Python?
Yes, environment variables let us switch settings easily between environments like development, staging, and production. By assigning different values (e.g., DEBUG=True
for development and DEBUG=False
for production), we can change application behavior without modifying code.
5. How do you check if an environment variable is True
in Python?
Environment variables are always strings. To check for a Boolean value:
import osdebug = os.getenv("DEBUG", "False").lower() in ("true", "1", "yes")
This method allows flexible truthy checks for values like “True”, “1”, or “yes”.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
Python Syntax Guide for Beginners
Learn Python syntax with this beginner-friendly guide. Understand Python indentation, print statements, variables, comments, user input, and more with examples. - Article
Environments
In this article, you'll learn about the different environments that a project can be in as it goes through the process of development and eventually being released. - Article
How to Build a Python Script: A Beginner’s Guide to Python Scripting
Learn scripting and how to build Python scripts from scratch. Set up your environment, structure your code, run the script, and explore real examples with tips to get started.
Learn more on Codecademy
- Free course
Intro to C#
Dive into C#, a scalable programming language that is easy to read and maintain.Beginner Friendly4 hours - Free course
Python for Programmers
An introduction to the basic syntax and fundamentals of Python for experienced programmers.Intermediate3 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours