Configuration & Data Formats

python-dotenv

The quiet helper that keeps your passwords out of your code and out of GitHub by accident.

Install it: pip install python-dotenv

What does it do?

python-dotenv reads a small file, typically named .env, filled with lines like API_KEY=abc123, and loads those values into a running program as if they’d been set directly on the computer. It works like a sealed envelope of settings handed to a program right before it starts, instead of writing sensitive details directly on the outside of the box for everyone to see. Developers keep secrets like database passwords and API keys in this file, then tell python-dotenv to load them in, keeping sensitive values separate from the actual program code. That .env file is meant to stay off shared code repositories entirely.

See it in action

This loads a secret value, like an API key, from a hidden settings file on disk so the program can use it without that secret being typed directly into the code.

import os
from dotenv import load_dotenv

load_dotenv()  # reads key=value pairs from a .env file
api_key = os.getenv("API_KEY")
print(api_key)

Why would a non-developer care?

This is one of the main reasons the code you write doesn’t need your passwords typed directly inside it, which matters a lot the moment that code gets shared, backed up, or accidentally posted publicly. It’s a small tool solving a problem that has caused real, embarrassing security incidents when skipped.

Real-world examples

Nearly every tutorial, startup codebase, and open-source Python project that talks to an external service, a database, an email provider, a payment processor, uses a .env file for its secrets, and python-dotenv is overwhelmingly the library that loads it. Companies have had API keys leaked publicly on GitHub because someone hardcoded a secret directly into their code instead of using a pattern like this one.

Who uses it

Developers of any experience level who need to keep secret credentials separate from source code, from solo hobbyists to production engineering teams.

How it compares to alternatives

It’s a much lighter-weight alternative to full secret-management systems like HashiCorp Vault or cloud providers’ secret managers, appropriate for local development and small projects rather than large-scale production security.

Fun fact

The .env file convention it popularized in Python actually originated with Ruby’s dotenv gem, and the pattern has since been copied into nearly every major programming language.

New to Python and want to actually try libraries like this yourself?

Find a beginner-friendly course

Related libraries