Env Tools
Tools for using .env files in Python. This library simplifies loading environment variables from `.env` files and accessing them with optional type casting and default values. As of version 2.4.0, it offers a stable API for managing application configurations, with minor releases for improvements and bug fixes.
Common errors
-
ModuleNotFoundError: No module named 'env_tools'
cause The `env-tools` package is not installed in your current Python environment.fixRun `pip install env-tools` in your terminal. -
env_tools.exceptions.EnvNotFoundError: Environment variable 'MY_VARIABLE' not found and no default provided.
cause You tried to access an environment variable using `get_env('MY_VARIABLE')` that is neither defined in your `.env` file, nor in your OS environment, and no `default` value was supplied to `get_env()`.fixEither define 'MY_VARIABLE' in your `.env` file or OS environment, or provide a default value: `get_env('MY_VARIABLE', default='some_value')`. -
ValueError: invalid literal for int() with base 10: 'not_an_int'
cause You used `cast_to_type=int` (or another type) with `get_env()`, but the value retrieved from the environment variable (e.g., 'not_an_int') could not be successfully converted to the specified type.fixEnsure the environment variable's value is compatible with the `cast_to_type` you are using (e.g., '123' for `int`, 'True'/'False' for `bool`). Implement validation or error handling if input might be malformed.
Warnings
- gotcha `get_env()` always returns a string by default. Remember to use the `cast_to_type` argument (e.g., `cast_to_type=int`, `cast_to_type=bool`) if you expect a non-string type.
- gotcha Since version 2.0.0, `load_env()` by default does *not* raise an `EnvNotFoundError` if the `.env` file is missing. It will simply proceed without loading variables from the file. If you require the `.env` file to be present, set `critical=True`.
- gotcha Environment variables explicitly set in the operating system always take precedence over variables defined in the `.env` file. Be aware that `load_env()` will not override existing OS environment variables.
Install
-
pip install env-tools
Imports
- load_env
from env_tools import load_env
- get_env
from env_tools import get_env
- EnvNotFoundError
from env_tools import EnvNotFoundError
Quickstart
import os
from env_tools import load_env, get_env, EnvNotFoundError
# --- Example .env file content (assume this is in a file named .env) ---
# MY_APP_DEBUG=True
# DATABASE_URL=postgresql://user:pass@host:5432/db
# API_KEY=abc-123-xyz
# WORKERS=4
# ----------------------------------------------------------------------
# Load environment variables from the .env file in the current directory.
# By default, load_env doesn't raise an error if the .env file is missing.
# Set critical=True to make file loading mandatory.
load_env()
# Access environment variables with optional type casting and defaults
debug_mode = get_env("MY_APP_DEBUG", cast_to_type=bool, default=False)
db_url = get_env("DATABASE_URL")
api_key = get_env("API_KEY", default="default_api_key_if_not_set")
workers = get_env("WORKERS", cast_to_type=int) # No default, will raise EnvNotFoundError if missing
print(f"Debug Mode: {debug_mode} (Type: {type(debug_mode)})")
print(f"Database URL: {db_url}")
print(f"API Key: {api_key}")
print(f"Workers: {workers} (Type: {type(workers)})")
# Demonstrating a missing variable without a default
try:
get_env("UNDEFINED_VAR_NO_DEFAULT")
except EnvNotFoundError as e:
print(f"\nCaught expected error for missing variable: {e}")
# OS environment variables take precedence over .env file values
os.environ['API_KEY'] = 'overridden_key_from_os'
# No need to reload load_env, subsequent get_env calls will check os.environ first
print(f"API Key (OS override): {get_env('API_KEY')}")
# Clean up the OS environment variable after the example
del os.environ['API_KEY']