load-dotenv
The `load-dotenv` library, currently at version 0.1.0, provides a lightweight wrapper that automatically and implicitly loads environment variables from `.env` files. It essentially re-exports the core functionality of the popular `python-dotenv` library, offering a simple interface to manage environment variables for development. It has a low release cadence given its wrapper nature.
Common errors
-
KeyError: 'MY_VAR' or TypeError: 'NoneType' object is not subscriptable
cause The environment variable `MY_VAR` was not loaded, not present in the `.env` file, or the `.env` file itself was not found/loaded when accessing `os.environ['MY_VAR']` or calling a method on `os.getenv('MY_VAR')` when it returns `None`.fixEnsure `load_dotenv()` is called early in your application's entry point. Verify `MY_VAR` exists in your `.env` file and that the file is correctly placed (or specify `dotenv_path`). Use `os.getenv('MY_VAR', 'default_value')` to provide fallbacks and prevent `TypeError`. -
Environment variable not updating / Old value of variable is loaded
cause `load_dotenv()` by default does not overwrite existing environment variables that were already set in the shell before the script runs.fixIf you intend to prioritize values from `.env` over existing shell variables, call `load_dotenv(override=True)`. -
'.env file not found' (when expecting variables to load)
cause The `load_dotenv()` function couldn't locate a `.env` file in the current directory or any parent directories as it searches upwards.fixPlace your `.env` file in the project's root directory. Alternatively, provide the explicit path to your `.env` file using the `dotenv_path` argument: `load_dotenv(dotenv_path='/path/to/your/.env')`.
Warnings
- gotcha `load_dotenv()` does not overwrite existing environment variables by default.
- gotcha The `.env` file location search behavior can be unexpected.
- gotcha Committing `.env` files to version control poses a significant security risk.
- gotcha Values with quotes or empty values are parsed literally, potentially leading to unexpected results.
Install
-
pip install load-dotenv
Imports
- load_dotenv
from dotenv import load_dotenv
from load_dotenv import load_dotenv
Quickstart
import os
from load_dotenv import load_dotenv
# Create a dummy .env file for demonstration
# In a real scenario, this file would exist beforehand
with open('.env', 'w') as f:
f.write('DB_HOST=localhost\n')
f.write('DB_USER=admin\n')
f.write('DB_PASSWORD=secret_password\n')
load_dotenv() # take environment variables from .env.
# Access environment variables
db_host = os.getenv("DB_HOST")
db_user = os.getenv("DB_USER")
db_password = os.getenv("DB_PASSWORD")
print(f"DB Host: {db_host}")
print(f"DB User: {db_user}")
print(f"DB Password: {db_password}")
# Clean up the dummy .env file
os.remove('.env')