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.1.0.tar.gz (21.4 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.1.0-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: env_loader_pro-0.1.0.tar.gz
  • Upload date:
  • Size: 21.4 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.1.0.tar.gz
Algorithm Hash digest
SHA256 f059934e9dc624827fbfcca808cad9197407b93cca8591fe97d99525bbdcf377
MD5 6a1b5dfc08ec124ebbfb5847fe263978
BLAKE2b-256 34fad4077ec55f04684037d91e25dc692e17cb29131e3013c3fe114585d52c6c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: env_loader_pro-0.1.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.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2ebe1fc60d0d8daf61a2cd686acbcf6b62f57c731e89a49127976b33900ec4db
MD5 c1affb403af729e2dd23a3c9a298fc9a
BLAKE2b-256 69dc3935095cf877ba0bda599fd1abe63675a751206b3d7d51e6a6d8541fddfa

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