Env Tools

2.4.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load environment variables from a `.env` file using `load_env()` and retrieve them with `get_env()`. It covers basic access, type casting (e.g., to bool or int), providing default values, and handling `EnvNotFoundError` for missing variables. It also highlights how OS environment variables take precedence over those in the `.env` file.

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']

view raw JSON →