Course contentsShow
← Python
Lesson 546 of 1,0608. Professional Tooling and PackagingFree lesson

Loading Configurations with the python-dotenv Library

Configure your application to automatically load environment variables from a local .env file during development and testing workflows.

In this lesson, you will learn how to automate the loading of environment variables from a local .env file into your application's environment during development.

Why use .env files?

As you have learned previously, separating configuration from code is essential for security and flexibility. While environment variables are great for production, manually setting them in your shell every time you work on a project is tedious and error-prone. The python-dotenv library solves this by reading a .env file—a simple text file containing KEY=VALUE pairs—and injecting those values into os.environ.

Implementing python-dotenv

To get started, first add python-dotenv to your development dependencies. Create a file named .env in your project root:

DATABASE_URL=postgres://user:password@localhost:5432/db
API_KEY=your-secret-key-here

To load these variables into your application, you should call load_dotenv() as early as possible—usually at the very top of your main entry point script (e.g., main.py):

import os
from dotenv import load_dotenv

# Load variables from .env into the environment
load_dotenv()

# Access them as you would any other environment variable
db_url = os.environ.get("DATABASE_URL")
api_key = os.environ.get("API_KEY")

print(f"Connecting to {db_url}")

Development vs. Production

The beauty of this approach is that load_dotenv() looks for the file in your current directory. In your local development workflow, the library finds the .env file and populates the environment. In your production environment, you typically rely on the server’s pre-configured environment variables instead. Because load_dotenv() does not override existing environment variables by default, it acts as a graceful "fallback" for development, ensuring your application code remains clean and environment-agnostic.

Key Takeaway: Using python-dotenv allows you to manage local development configurations in a standard .env file, keeping your application logic clean while providing a seamless transition to real environment variables in production.