Skip to main content

A typed, validated, and secure environment loader for Python projects with automatic type casting, validation, secret masking, and schema support.

Project description

env-loader-pro

Typed, validated, and secure environment variable loader with sensible defaults, secret masking, clear error messages, and advanced features.

🚀 Key Features

  • Load from .env + system env with configurable priority
  • Automatic type casting (int, bool, list, JSON)
  • Required/optional validation with helpful errors
  • Default values support
  • Secret masking for safe printing/logging
  • Environment variable expansion (${VAR} syntax)
  • Multiple environment support (.env.dev, .env.prod, etc.)
  • Runtime validation rules
  • Strict mode for unknown variables
  • Schema support (Pydantic models & dataclasses)
  • Export to JSON/YAML
  • Auto-generate .env.example
  • CLI tool for common operations

📦 Installation

pip install env-loader-pro

Optional Dependencies

# For Pydantic schema support
pip install env-loader-pro[pydantic]

# For YAML export
pip install env-loader-pro[yaml]

# For everything
pip install env-loader-pro[all]

🎯 Quickstart

Basic Usage

from env_loader_pro import load_env

config = load_env(
    required=["API_KEY"],
    types={"PORT": int, "DEBUG": bool},
    defaults={"PORT": 8080},
    priority="system"
)

print(config["PORT"])  # 8080 (int)
print(config["DEBUG"])  # True (bool)

Environment Variable Expansion

# .env file:
# BASE_URL=https://example.com
# API_ENDPOINT=${BASE_URL}/api

config = load_env()
print(config["API_ENDPOINT"])  # "https://example.com/api"

Multiple Environments

# Loads .env.prod if exists, falls back to .env
config = load_env(env="prod")

Validation Rules

config = load_env(
    types={"PORT": int},
    rules={
        "PORT": lambda v: 1024 < v < 65535
    }
)

List and JSON Parsing

# .env:
# DOMAINS=["a.com","b.com"]
# LIMITS=10,20,400

config = load_env(types={"DOMAINS": list, "LIMITS": list})
print(config["DOMAINS"])  # ["a.com", "b.com"]
print(config["LIMITS"])   # ["10", "20", "400"]

Schema Support (Pydantic)

from env_loader_pro import load_with_schema
from pydantic import BaseModel

class Config(BaseModel):
    port: int
    debug: bool
    api_key: str

config = load_with_schema(Config)
print(config.port)  # Typed access

Schema Support (Dataclass)

from env_loader_pro import load_with_schema
from dataclasses import dataclass

@dataclass
class Config:
    port: int
    debug: bool
    api_key: str

config = load_with_schema(Config)
print(config.port)  # Typed access

Export Config

config = load_env()
config.save("config.json", format="json")
config.save("config.yaml", format="yaml")

Strict Mode

# Warns about unknown variables not in schema
config = load_env(
    required=["API_KEY"],
    types={"PORT": int},
    strict=True
)

Safe Representation

config = load_env()
print(config.safe_repr())  # Secrets are masked
# {"API_KEY": "****1234", "PORT": 8080}

🛠️ CLI Tool

After installation, use the envloader command:

# Show environment variables
envloader show --env prod

# Export to JSON
envloader export --output config.json --format json

# Validate environment
envloader validate --required API_KEY PORT

# Generate .env.example
envloader generate-example --required API_KEY PORT --optional DEBUG

📚 Advanced Examples

Generate .env.example

from env_loader_pro import generate_env_example

generate_env_example(
    required=["API_KEY", "DB_URI"],
    optional=["DEBUG", "LOG_LEVEL"],
    defaults={"PORT": 8080, "DEBUG": False},
    types={"PORT": int, "DEBUG": bool},
    output_path=".env.example"
)

Complex Validation

config = load_env(
    required=["API_KEY"],
    types={
        "PORT": int,
        "TIMEOUT": int,
        "ALLOWED_HOSTS": list
    },
    rules={
        "PORT": lambda v: 1024 < v < 65535,
        "TIMEOUT": lambda v: v > 0,
        "ALLOWED_HOSTS": lambda hosts: len(hosts) > 0
    },
    defaults={"TIMEOUT": 30}
)

Multi-Environment Setup

.env          # Base configuration
.env.dev      # Development overrides
.env.staging  # Staging overrides
.env.prod     # Production overrides
# Automatically loads .env.prod + .env (prod overrides base)
config = load_env(env="prod")

🔒 Security Features

  • Automatic secret masking for keys containing: secret, key, token, password, pwd
  • Safe representation method prevents accidental log leaks
  • Strict mode helps catch configuration errors

📊 Comparison with python-dotenv

Feature python-dotenv env-loader-pro
Load .env ✔️ ✔️
Type casting ✔️
Required variable validation ✔️
Default values ✔️
Secrets masking ✔️
Typed output ✔️
Variable expansion ✔️
Multi-environment ✔️
Validation rules ✔️
Schema support ✔️
CLI tool ✔️
Export to JSON/YAML ✔️

🧪 Testing

pip install -e ".[test]"
pytest tests/

📝 License

Apache License 2.0 - See LICENSE file for details.

🤝 Contributing

Contributions welcome! Please open an issue or submit a PR.

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

env_loader_pro-0.2.0.tar.gz (21.5 kB view details)

Uploaded Source

Built Distribution

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

env_loader_pro-0.2.0-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file env_loader_pro-0.2.0.tar.gz.

File metadata

  • Download URL: env_loader_pro-0.2.0.tar.gz
  • Upload date:
  • Size: 21.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.2

File hashes

Hashes for env_loader_pro-0.2.0.tar.gz
Algorithm Hash digest
SHA256 74236b70f0774f950bd4782833190c849bf60e9025ed2969676d0689bdfb159b
MD5 484bbe40f65e11df9c3ff6a5ac81d1a2
BLAKE2b-256 cf399068bd71e6baa558452396f5ffd05b989366941328eeb7866b2d98560098

See more details on using hashes here.

File details

Details for the file env_loader_pro-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: env_loader_pro-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 16.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.2

File hashes

Hashes for env_loader_pro-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5c6afd2ecd7e7cd2dbf6bdb919891b11195bf06583b784432628990fdef86b7e
MD5 e6da00313e799c64b2d0d4dd6108a776
BLAKE2b-256 43edd8a4d2d2cc978fe6f4b0c9af80f203da4e0f60567448907a0feec5155d2c

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