philiprehberger-dotenv-cast
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.
Validating choices
Restrict a variable to a fixed set of allowed values:
mode = env.choice("MODE", ["dev", "staging", "prod"]) # raises ValueError if not in list
level = env.choice("LOG_LEVEL", ["debug", "info", "warn"], default="info", required=False)
Validating with regex
Validate a variable against a regex pattern (uses re.fullmatch):
version = env.regex("VERSION", r"\d+\.\d+\.\d+") # "1.2.3" ok, "abc" raises ValueError
slug = env.regex("SLUG", r"[a-z0-9-]+", default="app", required=False)
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, …) |
env.choice(name, options, default=None, required=True) |
Get variable validated against a list of allowed values |
env.regex(name, pattern, default=None, required=True) |
Get variable validated against a regex pattern (re.fullmatch) |
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:
License
Release files for philiprehberger-dotenv-cast 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| philiprehberger_dotenv_cast-0.4.0.tar.gz | 190.1 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| philiprehberger_dotenv_cast-0.4.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 197.5 kB
Release files / philiprehberger_dotenv_cast-0.4.0.tar.gz
| Download URL | philiprehberger_dotenv_cast-0.4.0.tar.gz |
|---|---|
| Size | 190.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
313f5c346d528033af05bc0a642b547f8c21ff6cf97db999a36b846715c65a24
|
|
BLAKE2b-256 checksum How to use checksums |
5c5fa6555a660ed12f20fb22e03be5b66755120d427d7ff749cefa5a6d79383d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.13
|
Release files / philiprehberger_dotenv_cast-0.4.0-py3-none-any.whl
| Download URL | philiprehberger_dotenv_cast-0.4.0-py3-none-any.whl |
|---|---|
| Size | 7.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f74c3ed8132282bcc07e6963d120d526a774b6e4cd168e722e6284db7eea94eb
|
|
BLAKE2b-256 checksum How to use checksums |
08ead495393b06320331b06786df82ff07b20ddd60cd26d45820dcdf80be7729
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.13
|