Skip to main content

Type-safe environment variable loading with casting and defaults.

Project description

philiprehberger-dotenv-cast

Tests PyPI version Last updated

Type-safe environment variable loading with casting and defaults.

Installation

pip install philiprehberger-dotenv-cast

Usage

from philiprehberger_dotenv_cast import env, load_dotenv

# Load a .env file into os.environ
load_dotenv()

# Read variables with type casting
host = env.str("HOST", "localhost")
port = env.int("PORT", 8080)
debug = env.bool("DEBUG", False)
tags = env.list("TAGS")  # "a,b,c" -> ["a", "b", "c"]

Boolean Casting

Boolean values are case-insensitive:

  • Truthy: "true", "1", "yes", "on"
  • Falsy: "false", "0", "no", "off"

List Splitting

# Default separator is ","
tags = env.list("TAGS")  # "a, b, c" -> ["a", "b", "c"]

# Custom separator
paths = env.list("PATHS", separator=":")

JSON Parsing

config = env.json("CONFIG")  # '{"key": "value"}' -> {"key": "value"}

Byte Sizes

Parse human-readable size strings into raw byte counts:

max_upload = env.bytes("MAX_UPLOAD")     # "10MB"  -> 10 * 1024**2
buffer = env.bytes("BUFFER", default=4096)  # "1.5KiB" -> 1536

Supported suffixes (case-insensitive): B, KB/KiB, MB/MiB, GB/GiB, TB/TiB. A bare number is treated as bytes.

Durations

Parse duration strings into datetime.timedelta values:

from datetime import timedelta

timeout = env.duration("TIMEOUT")           # "30s"     -> timedelta(seconds=30)
poll = env.duration("POLL_INTERVAL")        # "500ms"   -> timedelta(milliseconds=500)
ttl = env.duration("CACHE_TTL", default=timedelta(minutes=5))  # "1h30m" -> 1h30m

Supported units (lowercase): ms, s, m, h, d, w. Compound durations (1h30m) are summed.

Missing Variables

Variables without a default raise MissingEnvError:

from philiprehberger_dotenv_cast import env, MissingEnvError

try:
    secret = env.str("SECRET_KEY")  # raises if not set
except MissingEnvError:
    print("SECRET_KEY is required")

Loading .env Files

from philiprehberger_dotenv_cast import load_dotenv

# Load default .env
load_dotenv()

# Load a specific file
load_dotenv("config/.env.production")

API

Method / Function Description
env.str(key, default?) Get variable as string
env.int(key, default?) Get variable cast to int
env.float(key, default?) Get variable cast to float
env.bool(key, default?) Get variable cast to bool
env.list(key, separator?, default?) Get variable split into a list
env.json(key, default?) Get variable parsed as JSON
env.bytes(key, default?) Get variable parsed as a byte size (512KB, 2MiB, …)
env.duration(key, default?) Get variable parsed as a timedelta (30s, 1h30m, …)
load_dotenv(path?) Load a .env file into os.environ
Env Class for creating custom instances
MissingEnvError Raised when a required variable is missing

Development

pip install -e .
python -m pytest tests/ -v

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

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 Distribution

philiprehberger_dotenv_cast-0.3.0.tar.gz (8.7 kB view details)

Uploaded Source

Built Distribution

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

philiprehberger_dotenv_cast-0.3.0-py3-none-any.whl (6.7 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for philiprehberger_dotenv_cast-0.3.0.tar.gz
Algorithm Hash digest
SHA256 510e1f8dfa57cb888107e25c82d8a8c878527c8a98c110030ea404721c9323a4
MD5 9aed0c114f69bae3a90f6cbc3ec00253
BLAKE2b-256 d252c53a384edde370c74ce6d29d6067197179fee3a76cd8222cfbd6b41b156f

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for philiprehberger_dotenv_cast-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1edc0c6b6e59bdc93e74011403164d5a312228742c6839ddbf88f6883f546136
MD5 94bd3e766b2a37c0a1bca654d8843f53
BLAKE2b-256 ed8066d3f370ae67623b94329e33071c70a45c17d0d2903cb0fde5fe8e9b6ba3

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