Skip to main content

Simple and type-safe environment variables management for Python

Project description

easy-dotenv

PyPI version Python Versions License: MIT

Simple and type-safe environment variables management for Python.

Installation

pip install easy-dotenv

Usage

You can organize your environment variables by modules. For example:

# env_loader.py
from easy_dotenv import EnvConfig

class BaseEnv(EnvConfig):
    # Base application settings
    port: int
    api_key: str
    debug: bool = False     # Optional with default value
    workers: int = 4        # Optional with default value
    
class TelegramEnv(EnvConfig):
    # Telegram-specific settings
    bot_token: str
    chat_id: str
    channel_id: str = ''    # Optional with default empty string

# Both classes will look for .env in project root
base = BaseEnv('..')
telegram = TelegramEnv('..')

__all__ = ['base', 'telegram']

Then use it in your code:

from env_loader import base, telegram

# Access base configuration
print(f"Port: {base.port}")
print(f"API Key: {base.api_key}")
print(f"Debug mode: {base.debug}")    # False if not set
print(f"Workers: {base.workers}")     # 4 if not set

# Access Telegram configuration
print(f"Bot Token: {telegram.bot_token}")
print(f"Chat ID: {telegram.chat_id}")
print(f"Channel ID: {telegram.channel_id}")  # Empty string if not set

Your .env file:

# Base
PORT=8000
API_KEY=your_api_key_here
DEBUG=true

# Telegram
BOT_TOKEN=your_bot_token_here
CHAT_ID=your_chat_id_here
CHANNEL_ID=optional_channel_id

Features

  • Type validation with automatic conversion
  • Required and optional variables
  • Default values
  • .env file support with flexible path resolution
  • Clean and simple API
  • Full type hints support
  • No code duplication

.env File Location

The path to the .env file can be specified in several ways:

  • '.env' - Look for .env in the same directory as the config file
  • '..' - Look for .env in the project root (where pyproject.toml/setup.py is located)
  • 'config/.env' - Look in a subdirectory
  • '../.env' - Look in the parent directory
  • None - Use python-dotenv's default behavior

Type Conversion

The library automatically converts environment variables to the specified types:

class Env(EnvConfig):
    # String values (no conversion needed)
    api_key: str
    database_url: str
    
    # Integer values
    port: int                # "8000" -> 8000
    workers: int = 4         # Default: 4
    
    # Boolean values
    debug: bool = False      # Default: False
    verbose: bool            # "true"/"1" -> True, "false"/"0" -> False

Error Handling

The environment validation happens when you initialize the configuration:

from easy_dotenv import EnvConfig, EnvMissingError, EnvTypeError, EnvFileNotFoundError

try:
    class Env(EnvConfig):
        api_key: str         # Required
        port: int           # Required
        debug: bool = False  # Optional
    
    env = Env('..')  # Look for .env in project root
except EnvMissingError as e:
    print("Missing environment variables:", e)
except EnvTypeError as e:
    print("Invalid environment variable type:", e)
except EnvFileNotFoundError as e:
    print("Could not find .env file:", e)  # Wrong path or no project root found

Development

Setup

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate  # Linux/MacOS
# or
# venv\Scripts\activate  # Windows

# Install with development dependencies
pip install -e ".[dev]"

Running Tests

# Run tests
pytest

# Run tests with coverage
pytest --cov=easy_dotenv

The test suite includes:

  • Required variables validation
  • Optional variables with defaults
  • Type conversion (including boolean values)
  • Error handling for missing variables
  • Error handling for invalid types
  • Mixed required and optional variables

License

MIT

Requirements

  • Python 3.7 or higher
  • python-dotenv>=0.19.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

easy_dotenv-0.3.1.tar.gz (6.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

easy_dotenv-0.3.1-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

Details for the file easy_dotenv-0.3.1.tar.gz.

File metadata

  • Download URL: easy_dotenv-0.3.1.tar.gz
  • Upload date:
  • Size: 6.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for easy_dotenv-0.3.1.tar.gz
Algorithm Hash digest
SHA256 e9039f9b084880d9842f1decedc5a8f60d47ed63cf9ed92d3af83dbff7442a04
MD5 32ad8ffb07d3316198bfe932ab6f2cbc
BLAKE2b-256 f610b0b810cfb8fbcb754430a5270d19cfd847429034ced6a2e07594ca06f836

See more details on using hashes here.

File details

Details for the file easy_dotenv-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: easy_dotenv-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 6.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for easy_dotenv-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c598dab774f66c27e44e1c72fc5e788e716c97e9147a8daaaa5e41368d1c858d
MD5 319cae22dcc2f44825f7f58a13ab866b
BLAKE2b-256 70e15e44ec7c5f0ac8471e13fbe9f725bd156c6888da2bd0f18ca7fca6abc026

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page