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.3.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.3.0-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: env_loader_pro-0.3.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.3.0.tar.gz
Algorithm Hash digest
SHA256 784c20575e965117231f0096f30cdc72cd5c07ccd2fba41a549de2490ccb0b0f
MD5 1aa5302713930136ae9303989f4c2196
BLAKE2b-256 51935e5db13da4d6d828d66b26c5e7bae998bf056b9c8e75376c9b0db65c225d

See more details on using hashes here.

File details

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

File metadata

  • Download URL: env_loader_pro-0.3.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.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bf6dd5f5b50ca7fbfc2c172b8477fae344ced8323ba7e339a51ed8dbd0e95ce1
MD5 11abf637d53a0f4b8c8fabdef8bc1682
BLAKE2b-256 402fd4763a1394234bda1817c22fbf4c780498900446fa4abcb152f6b5e765fc

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