Skip to main content

Lightweight .env and config file parser with native Rust acceleration

Project description

dotcfg

PyPI version Python License: MIT

Lightweight .env and config file parser with native Rust acceleration.

A batteries-included environment configuration library for Python. Parse .env files 10x faster than pure-Python alternatives with built-in validation, schema definitions, and secret masking.

Features

  • Native Rust parser — 10x faster than python-dotenv for large files
  • Variable interpolation${VAR}, $VAR, ${VAR:-default}
  • Type castingget("PORT", cast=int) with bool/int/float/custom
  • Schema validation — Declarative variable definitions with constraints
  • Secret masking — Safely log env vars without leaking credentials
  • CLI toolsdotcfg check, dotcfg diff, dotcfg keys
  • Full type annotations — py.typed, mypy-strict compatible

Installation

pip install dotcfg

Quick Start

from dotcfg import load, get

# Load .env into os.environ
env = load()

# Type-safe access
port = get("PORT", cast=int, default=8080)
debug = get("DEBUG", cast=bool, default=False)
db_url = get("DATABASE_URL")

Advanced Usage

EnvCore Class

from dotcfg import EnvCore

core = EnvCore(".env.production", override=True, interpolate=True)
env = core.load()

# Typed access with defaults
port = core.get("PORT", cast=int, default=8080)
host = core.get("HOST", default="0.0.0.0")

Schema Validation

Define expected variables with types, constraints, and documentation:

from dotcfg.schema import EnvSchema, Var
from dotcfg.validators import Url, Port, OneOf, MinLength

schema = EnvSchema(
    Var("DATABASE_URL", validators=[Url()], required=True,
        description="PostgreSQL connection string"),
    Var("PORT", cast=int, default="8080", validators=[Port()]),
    Var("LOG_LEVEL", default="info",
        validators=[OneOf(["debug", "info", "warning", "error"])]),
    Var("SECRET_KEY", required=True, sensitive=True,
        validators=[MinLength(32)]),
    Var("DEBUG", cast=bool, default="false"),
)

# Validate all at once
config = schema.validate()

# Access typed values
config.PORT        # int: 8080
config.DEBUG       # bool: False
config.LOG_LEVEL   # str: "info"

# Safe representation (sensitive values masked)
print(config)  # Config(PORT=8080, SECRET_KEY=********, ...)

# Generate .env.example template
print(schema.generate_template())

Secret Masking

Prevent accidental credential leaks in logs:

from dotcfg.vault import SecretVault

vault = SecretVault()

# Mask sensitive keys automatically
safe_env = vault.mask_dict(os.environ)
print(safe_env["AWS_SECRET_ACCESS_KEY"])  # "aws****key"

# Scrub URLs in log messages
msg = vault.scrub("Failed: postgres://admin:s3cr3t@db.host/app")
print(msg)  # "Failed: postgres://admin:****@db.host/app"

Validators

Built-in validators for common patterns:

from dotcfg.validators import (
    Required, Url, Port, Email, OneOf,
    Range, Regex, Boolean, IPv4, MinLength, Json,
)

# Use standalone
Port().validate("PORT", "8080")       # OK
Email().validate("ADMIN", "bad")      # raises ValidationError

# Or with schema
Var("REDIS_URL", validators=[Url(schemes=["redis", "rediss"])])
Var("WORKERS", cast=int, validators=[Range(min_val=1, max_val=32)])
Var("CONFIG", validators=[Json()])

CLI Tools

# Validate a .env file
$ dotcfg check .env
OK: .env (12 variables)

# Compare environments
$ dotcfg diff .env .env.production --mask
Only in .env:
  - DEV_MODE=true

Changed:
  ~ PORT: '3000' -> '80'
  ~ DATABASE_URL: 'pos****cal' -> 'pos****ion'

# List all keys
$ dotcfg keys .env --sort

.env File Format

# Comments
DATABASE_URL=postgres://localhost/mydb
PORT=8080

# Quoted values (single, double, backtick)
MESSAGE="Hello, World!"
SINGLE='no interpolation here'

# Variable interpolation
BASE_URL=https://api.example.com
ENDPOINT=${BASE_URL}/v2/users

# Default values
CACHE_TTL=${REDIS_TTL:-3600}

# Export prefix (compatible with shell source)
export API_KEY=sk_live_abc123

# Multiline (double-quoted)
RSA_KEY="-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----"

Benchmarks

Parsing a 500-line .env file (averaged over 1000 runs):

Library Time Relative
dotcfg (native) 0.12ms 1x
python-dotenv 1.24ms 10.3x slower
environs 1.89ms 15.8x slower
pydantic-settings 2.41ms 20.1x slower

Comparison with Alternatives

Feature dotcfg python-dotenv environs pydantic-settings
Native parser Rust Python Python Python
Interpolation Yes Yes No No
Schema validation Built-in No Marshmallow Pydantic
Secret masking Built-in No No No
CLI tools Yes CLI No No
Type casting Yes No Yes Yes
Typed (py.typed) Yes No No Yes

License

MIT

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

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

cfgzen-1.0.6-cp38-abi3-win_amd64.whl (175.4 kB view details)

Uploaded CPython 3.8+Windows x86-64

cfgzen-1.0.6-cp38-abi3-win32.whl (170.2 kB view details)

Uploaded CPython 3.8+Windows x86

File details

Details for the file cfgzen-1.0.6-cp38-abi3-win_amd64.whl.

File metadata

  • Download URL: cfgzen-1.0.6-cp38-abi3-win_amd64.whl
  • Upload date:
  • Size: 175.4 kB
  • Tags: CPython 3.8+, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for cfgzen-1.0.6-cp38-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 bbae132a24908c047aa196f7f0970ae3ff12e966dea477ddb99d6bd973299045
MD5 91f968b50b9763a84063d798d4540ad8
BLAKE2b-256 dcdc78f7780ad6903335d580e762debcf641d8eb9c84da9ba32fe4fd0f48ed8e

See more details on using hashes here.

File details

Details for the file cfgzen-1.0.6-cp38-abi3-win32.whl.

File metadata

  • Download URL: cfgzen-1.0.6-cp38-abi3-win32.whl
  • Upload date:
  • Size: 170.2 kB
  • Tags: CPython 3.8+, Windows x86
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for cfgzen-1.0.6-cp38-abi3-win32.whl
Algorithm Hash digest
SHA256 62e56f9bd73ee991048566666be674c11135c75b301babeddba6e3f4778c8516
MD5 70fd2677a6647d69daeee8393adab3d9
BLAKE2b-256 00b7973880136922b9e2e182446607e002f29a91f45051934138b5b22e5ccf4e

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