Envparse: Simple Environment Variable Parsing
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
-
KeyError: 'ENV_VAR_NAME'
cause Attempting to access an environment variable that is not set, and no default value or schema is provided.fixProvide a default value: `value = env('ENV_VAR_NAME', default='fallback_value')`. Alternatively, use the `Env` class with a defined schema, which raises a `ConfigurationError` for missing variables, providing a more specific error. -
assert mail_enabled is True # where MAIL_ENABLED=0 in .env
cause Boolean environment variables are parsed as strings ('True', 'False', '1', '0') by default. Without explicit casting, `env('DEBUG')` might return the string 'True' or '0', which evaluates to `True` in a boolean context, but `is True` will fail for the string 'True' and '0' is not `False`.fixAlways explicitly cast boolean-like environment variables: `mail_enabled = env('MAIL_ENABLED', type=bool)` or `mail_enabled = env.bool('MAIL_ENABLED')`. This will correctly convert '0', 'False', 'off' to `False` and '1', 'True', 'on' to `True`. -
AttributeError: 'envparse.env.Env' object has no attribute 'json'
cause Attempting to use convenience methods like `env.json()` or `env.url()` which might not be available in older versions or are not explicitly imported.fixFor basic types, use explicit casting: `json_data = env('JSON_VAR', type=dict)`. Ensure you are using the correct method signatures as per the specific version of `envparse` being used, or consult the GitHub README for the most current API if these convenience methods are desired and not working.
Warnings
- gotcha The `env.read_envfile()` method uses `os.environ.setdefault()`, which means environment variables already set in the operating system will *not* be overridden by values in the `.env` file. This can lead to unexpected behavior if you intend for the `.env` file to always be the source of truth.
- gotcha There is a discrepancy in keyword arguments for type casting between the PyPI 0.2.0 description (`type`, `subtype`) and the current GitHub README (`cast`, `subcast`). For the installed 0.2.0 version from PyPI, use `type=some_type` and `subtype=some_nested_type` (e.g., for lists). If installing directly from GitHub, `cast` and `subcast` might be required.
- deprecated The `envparse` library, at version 0.2.0, has not seen a new release since December 2015. While functional, it may lack features or bug fixes present in more actively maintained environment variable parsing libraries. Consider alternatives like `python-decouple` or `environs` if active development and newer features are a priority.
Install
-
pip install envparse -
pip install git+https://github.com/rconradharris/envparse.git
Imports
- env
from envparse import env
- Env
from envparse import Env
Quickstart
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')