5  dotenv: Manage Configs and Sensitive Info

5.1 Why .env file and python-dotenv

When developing a Python project, you often need to manage configuration settings and sensitive information. These settings are typically user-specific (for example, input/output directories on your computer) or sensitive (such as API keys and database credentials) and should not be hard-coded into your source code, especially when collaborating with others. Storing these values in environment variables is a common approach, and the python-dotenv package simplifies this process by loading variables from a .env file into your Python’s process environment.

5.2 Using python-dotenv

python-dotenv is a third-party package, so you first need to install it. You can do this using uv,

uv add python-dotenv

Next, create a .env file in the root directory of your project to store your environment variables. (Note that files that start with . are hidden files by default on Linux-based systems.) Here’s an example of what a .env file might look like:

# .env file

# API keys and sensitive information
OPENAI_API_KEY=sk-123abc456xyz

# Application settings
DEBUG=True

# Data directories
DATA_INPUT_DIR=/path/to/data/input
DATA_OUTPUT_DIR=/path/to/data/output

To use these environment variables in your Python code, you need to load them using the load_dotenv() function from the dotenv module. Here’s an example of how to do this:

from dotenv import load_dotenv
import os

# Load environment variables from .env
load_dotenv()

# Access variables like normal environment variables
api_key = os.getenv("OPENAI_API_KEY")
debug_mode = os.getenv("DEBUG") == "True"
data_input = os.getenv("DATA_INPUT_DIR")
data_output = os.getenv("DATA_OUTPUT_DIR")

# Use the variables in your code
print("API Key:", api_key[:10] + "...")  # Mask key for safety
print("Debug mode:", debug_mode)
print("Input data directory:", data_input)
print("Output data directory:", data_output)

In this example, we first import the load_dotenv function and the os module. We then call load_dotenv() to load the variables from the .env file into the environment. After that, we can access these variables using os.getenv().

Note that load_dotenv() loads the variables into Python’s process environment (i.e., os.environ), not into your operating system’s global environment.

IMPORTANT: If you use Git for version control, make sure to add the .env file to your .gitignore to prevent it from being committed to the repository, as it may contain sensitive information.

5.3 Learning Resources

To learn more about python-dotenv, refer to its official documentation.