Articles

Python Env Vars: Complete Guide to Environment Variables

Learn how to set, get, and manage environment variables in Python using `os.environ` and `.env` files. Step-by-step guide with code examples and best practices.

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 os
API_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.

Related Course

Intro to C#

Dive into C#, a scalable programming language that is easy to read and maintain. Try it for free

How 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 os
api_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 os
api_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_dotenv
import os
load_dotenv() # This loads variables from .env into os.environ
api_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-key
DATABASE_URL=postgres://user:pass@localhost/db
DEBUG=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=mysecret
DEBUG=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 os
for 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 os
debug = os.getenv("DEBUG", "False").lower() in ("true", "1", "yes")

This method allows flexible truthy checks for values like “True”, “1”, or “yes”.

Codecademy Team

'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 team