This explicit, ordered loading ensures that the values in your .env.python.local take precedence over all other files, giving you the ultimate local control.
from pydantic import PostgresDsn from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): # Pydantic will auto-map uppercase env variables to these fields DATABASE_URL: str API_KEY: str DEBUG_MODE: bool = False LOG_LEVEL: str = "INFO" # Configure Pydantic to read .env.python.local with priority over .env model_config = SettingsConfigDict( env_file=('.env', '.env.python.local'), env_file_encoding='utf-8', extra='ignore' # Ignores undefined extra variables in the env files ) # Instantiate settings settings = Settings() print(f"Database Target: settings.DATABASE_URL") print(f"Log Level Configured: settings.LOG_LEVEL") Use code with caution.
If you must put a real (but low-risk) API key in .env.python.local (e.g., a development SendGrid key), treat it like a password. Rotate it monthly.
# .env.python.local PYTHONPATH="/Users/username/projects/my_project/src" VIRTUAL_ENV="/Users/username/.local/share/virtualenvs/my_project-vE82x" Use code with caution. 2. Debugging and Profiling Flags .env.python.local
Here are some benefits of using .env.python.local :
Mismanaging environment variables poses a massive security risk. Follow these strict rules to ensure your local configurations remain secure:
By adopting .env.python.local in your Python projects today, you eliminate "works on my machine" bugs before they happen. You give your team the power to customize their environment without stepping on each other's toes. And you build a configuration system that scales from a hello_world.py script to a distributed microservice architecture. This explicit, ordered loading ensures that the values
When scaffolding your next Python project, do this immediately:
for local-only overrides) is used to store sensitive data like API keys or database URLs so they aren't hardcoded in your script. : Create a plain text file named in your project folder.
This public link is valid for 7 days and shares a thread, including any personal information you added. This link or copies made by others cannot be deleted. If you share with third parties, their policies apply. Can’t copy the link right now. Try again later. Rotate it monthly
This public link is valid for 7 days and shares a thread, including any personal information you added. This link or copies made by others cannot be deleted. If you share with third parties, their policies apply. Can’t copy the link right now. Try again later.
load_dotenv(BASE_DIR / ".env.python", override=True)
By default, python-dotenv looks for a file named exactly .env . To load your custom .env.python.local file, you must specify the path explicitly in your Python code. Here is a comprehensive example: