Python for AIPython for AI
Tools

Using .env files

The easy way to manage secrets

When you write Python code, you often need to store secret keys or configuration values. Let's learn an easy and safe way to handle them.

What is a .env file?

A .env file is a plain text file. It holds environment variables. Think of it as a small file that tells your program important setup details.

It keeps sensitive information, like API keys or database passwords, separate from your main code. This is super important for security and flexibility.

The period at the beginning of .env means it's often hidden by default on many operating systems. Don't worry, your Python code can still find it!

Basic setup

Let's get your project ready to use .env files.

1. Install python-dotenv

First, you need a small library called python-dotenv. It helps your Python code read these special files.

bash
pip install python-dotenv

2. Create .env file

In the root (top-level) directory of your Python project, create a new file named .env. Make sure it's exactly .env, with the dot!

This file should be in the same folder where your main Python script runs from.

Inside this .env file, add your variables. Each line is a KEY=VALUE pair. No spaces around the equals sign, usually.

text
API_KEY=your_super_secret_api_key_123
DATABASE_URL=postgres://user:pass@host:port/dbname
DEBUG_MODE=True

3. Load in Python

Now, in your Python script, you need to tell python-dotenv to load the variables from your .env file.

python
from dotenv import load_dotenv
import os

load_dotenv() # take environment variables from .env.

api_key = os.getenv("API_KEY")
debug_mode = os.getenv("DEBUG_MODE")

print(f"API Key: {api_key}")
print(f"Debug Mode: {debug_mode}")

The load_dotenv() function looks for the .env file. Then, os.getenv() fetches the values for you. It's that simple!

Critical: Add to .gitignore

To prevent accidentally sharing your secrets, add .env to your project's .gitignore file. This tells Git to ignore it.

text
# Ignore environment files
.env
*.env

Complete example

Here's how a small project might look with a .env file and a Python script using it.

text
# .env file
SECRET_KEY=my_super_secret_key
DATABASE_USER=admin
python
# main.py
from dotenv import load_dotenv
import os

load_dotenv()

secret = os.getenv("SECRET_KEY")
db_user = os.getenv("DATABASE_USER")

print(f"Using secret: {secret}")
print(f"Database user: {db_user}")

Show others what they need

When you share your project, others need to know which environment variables to set. You can provide an example file.

Create a file called .env.example (or .env.sample). This file has the same keys as your .env but with empty or placeholder values.

text
# .env.example
API_KEY=
DATABASE_URL=
DEBUG_MODE=False # Example default

This file *can* be committed to Git. It helps other developers understand what variables they need to create in their *own* .env file.

Rules for .env files

  • One KEY=VALUE pair per line.
  • No spaces around = might be slightly safer, though python-dotenv often handles them.
  • String values usually don't need quotes, but if they contain spaces or special characters, you can use single or double quotes.
  • Lines starting with # are comments and are ignored.
text
# This is a comment
MY_VARIABLE=hello world # This comment here might be ignored by some tools
ANOTHER_VAR="value with spaces"
HTTP_PORT=8080

Common patterns

It's common to have different .env files for different environments (e.g., development, testing, production). However, for beginners, one .env for local development is usually enough.

You often retrieve values at the start of your main script or an app.py file.

Quick tips

  • Always use os.getenv() to fetch variables, not os.environ directly, as getenv returns None if the variable isn't set, which is safer.
  • Convert string values to the correct type (e.g., 'True' to True, '123' to 123) in your Python code.
python
import os
from dotenv import load_dotenv

load_dotenv()

API_KEY = os.getenv("API_KEY")
DEBUG = os.getenv("DEBUG_MODE", "False").lower() == "true" # Provide a default
PORT = int(os.getenv("PORT", 8000)) # Convert to integer

print(f"Debug is {DEBUG}, Port is {PORT}")

What's next?

Now you know how to keep your secrets safe and your configurations flexible using .env files. This is a crucial skill for any developer!

Practice adding a .env file to your next project. Try storing different types of data and retrieving them.