Envparse: Simple Environment Variable Parsing

0.2.0 · active · verified Thu Apr 16

Envparse is a Python utility designed for parsing environment variables, inspired by the 12 Factor App methodology. It simplifies configuration management by providing a wrapper around `os.environ` that handles type casting and default values, reducing boilerplate code. The current stable version on PyPI is 0.2.0, released in December 2015, indicating a mature but infrequently updated library.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both the standard `env` object and the schema-based `Env` class. It shows how to load variables, cast them to specific types (explicitly and implicitly for built-in types), and provide default values. A dummy `.env` file is created and cleaned up for a self-contained example. Note the use of `type` for explicit casting and `env.int()` for implicit casting of built-in types, as per version 0.2.0 documentation.

import os
from envparse import env, Env

# Create a dummy .env file for demonstration
with open('.env', 'w') as f:
    f.write('DATABASE_URL=sqlite:///db.sqlite
')
    f.write('DEBUG=True
')
    f.write('ALLOWED_HOSTS=localhost,127.0.0.1
')
    f.write('WORKERS=4
')

# Load .env file (optional, envparse searches parent directories too)
env.read_envfile()

# --- Standard usage (env object) ---

db_url = env('DATABASE_URL', default='postgres://localhost/mydb')
debug_mode = env('DEBUG', type=bool, default=False)
workers = env.int('WORKERS', default=2) # Implicit type casting for built-in types

print(f"[Standard] DB URL: {db_url}")
print(f"[Standard] Debug Mode: {debug_mode} (type: {type(debug_mode)})")
print(f"[Standard] Workers: {workers} (type: {type(workers)})")

# --- Usage with schema (Env class) ---

# Define a schema for environment variables
config_schema = Env(
    ALLOWED_HOSTS=(list, ['*']), # (type, default)
    SECRET_KEY=str # type only, no default, will raise ConfigurationError if missing
)

# Load config from schema
allowed_hosts = config_schema('ALLOWED_HOSTS')

print(f"[Schema] Allowed Hosts: {allowed_hosts} (type: {type(allowed_hosts)})")

# Clean up dummy .env file
os.remove('.env')

view raw JSON →