.env Configuration
The DotEnvConfigFile manages the .env file for local environment variables.
Overview
Creates a .env file that:
- Stores local environment variables
- Automatically excluded from version control (in
.gitignore) - Located at the project root
- User-managed content (pyrig doesn't write to it)
- Loaded using python-dotenv library
Inheritance
Inherits from: DictConfigFile
What this means:
- Inherits from DictConfigFile (dict-based configuration)
- Custom
_load()and_dump()implementations - Read-only from pyrig's perspective
- Users manage content manually
File Location
Path: .env (project root)
Extension: env - Environment file (dot added by separator).
Filename: Empty string to produce .env (not env.env).
Special filename handling: get_filename() returns "" to create a
dotfile.
How It Works
Automatic Generation
When initialized via uv run pyrig mkroot, the file is created:
- Empty file: Created if it doesn't exist
- Git exclusion: Automatically added to
.gitignore - User-managed: Pyrig doesn't write to this file
Loading Environment Variables
The .env file is loaded using the python-dotenv library's dotenv_values()
function, which parses the file and returns a dictionary mapping variable names
to their values.
Dump Protection
Pyrig prevents accidental writes to .env files. If you attempt to dump
a non-empty configuration to this file, it will raise a ValueError. This is
intentional - the .env file is user-managed and should be edited manually.
Dumping an empty dict {} is allowed (which is what pyrig does during
initialization).
Usage
Automatic Creation
uv run pyrig mkroot
Adding Environment Variables
Manually edit the .env file:
# .env
DATABASE_URL=postgresql://localhost/mydb
API_KEY=your-secret-key
DEBUG=true
Loading in Python
from dotenv import load_dotenv
import os
# Load .env file
load_dotenv()
# Access variables
database_url = os.getenv("DATABASE_URL")
api_key = os.getenv("API_KEY")
debug = os.getenv("DEBUG", "false").lower() == "true"
Using with pyrig
from pyrig.dev.configs.dot_env import DotEnvConfigFile
# Load all variables
env_vars = DotEnvConfigFile.load()
print(env_vars["DATABASE_URL"])
Validation Logic
The validation checks if the .env file exists. The file can be empty - pyrig
only requires that it exists on disk.
Required element: File must exist (can be empty).
Best Practices
- Never commit: Keep
.envout of version control - Use .env.example: Create a template with dummy values
- Document variables: Add comments explaining each variable
- Keep secrets safe: Don't share
.envfiles - Use different files:
.env.local,.env.testfor different environments