Envs
Envs is a Python library (v1.4) designed for easy and typed access to environment variables. It automatically handles the parsing of environment variable values into various Python types, including strings, booleans, lists, tuples, integers, floats, and dictionaries. The library was last released in December 2021, suggesting a low-to-moderate release cadence, with updates as needed.
Warnings
- gotcha When defining default values for complex types (lists, dicts), ensure the default is a new instance each time to avoid mutable default argument issues. For example, `some_list: list = env('VAR', [])` is fine for `envs` as `env` will create a new default if not found. However, if manually implementing similar logic, one might fall into this Python common pitfall.
- gotcha The library parses string representations of booleans, lists, tuples, and dicts. Incorrect string formatting for these types in environment variables will lead to parsing errors or unexpected values. For instance, a non-JSON string for a dict type will fail.
- deprecated Older versions of the library (prior to 1.x) might have different API signatures or less robust type conversion. While the current PyPI version is 1.4, if using a very old, unlisted version, expect potential incompatibilities.
- gotcha The `env` callable raises `KeyError` by default if a required environment variable is not found and no default value is provided. This is intentional for explicitness but can be a surprise if not expected.
Install
-
pip install envs
Imports
- env
from envs import env
- Env
from envs import Env
Quickstart
import os
from envs import env, Env
os.environ['APP_DEBUG'] = 'true'
os.environ['API_KEY'] = 'your_api_key_123'
os.environ['THRESHOLD'] = '100'
os.environ['FEATURE_FLAGS'] = 'featureA,featureB'
os.environ['DB_SETTINGS'] = '{"host": "localhost", "port": 5432}'
class AppSettings(Env):
debug: bool = env('APP_DEBUG', False)
api_key: str = env('API_KEY')
threshold: int = env('THRESHOLD', 50)
feature_flags: list[str] = env('FEATURE_FLAGS', [])
db_settings: dict = env('DB_SETTINGS', {})
settings = AppSettings()
print(f"Debug mode: {settings.debug} (type: {type(settings.debug)})")
print(f"API Key: {settings.api_key} (type: {type(settings.api_key)})")
print(f"Threshold: {settings.threshold} (type: {type(settings.threshold)})")
print(f"Feature Flags: {settings.feature_flags} (type: {type(settings.feature_flags)})")
print(f"DB Settings: {settings.db_settings} (type: {type(settings.db_settings)})")
# Direct access without a schema
direct_api_key = env('API_KEY', '')
print(f"Direct API Key: {direct_api_key} (type: {type(direct_api_key)})")