Simplified environment variable parsing with type casting, validation, and framework integration
—
Complex data structure parsing including lists, dictionaries, and JSON with support for nested type casting, custom delimiters, and flexible serialization formats.
Parse delimited strings into Python lists with optional element type casting and custom delimiter support.
def list(self, name: str, default=..., subcast=None, *, delimiter=",", validate=None, **kwargs):
"""
Parse environment variable as list.
Parameters:
- name: str, environment variable name
- default: list, default value if variable not set (optional)
- subcast: type or callable for element type conversion (optional)
- delimiter: str, character(s) used to split the string (default: ",")
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
list: List of elements, optionally type-cast
Notes:
Empty string returns empty list. Subcast applies to each list element.
"""Usage examples:
import os
from environs import env
# Basic list parsing
os.environ["TAGS"] = "web,api,python"
tags = env.list("TAGS") # => ["web", "api", "python"]
# List with type casting
os.environ["PORTS"] = "8080,8081,8082"
ports = env.list("PORTS", subcast=int) # => [8080, 8081, 8082]
# List with custom delimiter
os.environ["COORDINATES"] = "23.3 50.0 -1.2"
coords = env.list("COORDINATES", subcast=float, delimiter=" ") # => [23.3, 50.0, -1.2]
# Empty list handling
os.environ["EMPTY_LIST"] = ""
empty = env.list("EMPTY_LIST") # => []
# Default value
default_tags = env.list("MISSING_TAGS", ["default"]) # => ["default"]Parse key-value string representations into Python dictionaries with support for nested type casting and custom delimiters.
def dict(self, name: str, default=..., *, subcast_keys=None, subcast_values=None,
delimiter=",", key_value_delimiter="=", validate=None, **kwargs):
"""
Parse environment variable as dictionary.
Parameters:
- name: str, environment variable name
- default: dict, default value if variable not set (optional)
- subcast_keys: type or callable for key type conversion (optional)
- subcast_values: type or callable for value type conversion (optional)
- delimiter: str, character(s) separating key-value pairs (default: ",")
- key_value_delimiter: str, character(s) separating keys from values (default: "=")
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
dict: Dictionary with optionally type-cast keys and values
"""Usage examples:
import os
from environs import env
# Basic dictionary parsing
os.environ["CONFIG"] = "host=localhost,port=8080,debug=true"
config = env.dict("CONFIG") # => {"host": "localhost", "port": "8080", "debug": "true"}
# Dictionary with value type casting
os.environ["LIMITS"] = "max_connections=100,timeout=30,retries=3"
limits = env.dict("LIMITS", subcast_values=int) # => {"max_connections": 100, "timeout": 30, "retries": 3}
# Dictionary with both key and value casting
os.environ["WEIGHTS"] = "1=0.5,2=0.3,3=0.2"
weights = env.dict("WEIGHTS", subcast_keys=int, subcast_values=float) # => {1: 0.5, 2: 0.3, 3: 0.2}
# Custom delimiters
os.environ["LOCATIONS"] = "x:234 y:123 z:456"
locations = env.dict("LOCATIONS", subcast_values=int, delimiter=" ", key_value_delimiter=":")
# => {"x": 234, "y": 123, "z": 456}Parse JSON-formatted strings into Python objects with full JSON specification support.
def json(self, name: str, default=..., *, validate=None, **kwargs):
"""
Parse environment variable as JSON.
Parameters:
- name: str, environment variable name
- default: any JSON-serializable type, default value if variable not set (optional)
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
any: Parsed JSON object (dict, list, str, int, float, bool, None)
Raises:
EnvValidationError: If value is not valid JSON
"""Usage examples:
import os
from environs import env
# Simple JSON object
os.environ["API_CONFIG"] = '{"endpoint": "https://api.example.com", "timeout": 30, "retries": 3}'
api_config = env.json("API_CONFIG")
# => {"endpoint": "https://api.example.com", "timeout": 30, "retries": 3}
# JSON array
os.environ["ALLOWED_HOSTS"] = '["localhost", "127.0.0.1", "example.com"]'
hosts = env.json("ALLOWED_HOSTS") # => ["localhost", "127.0.0.1", "example.com"]
# Complex nested JSON
os.environ["DATABASE_CONFIG"] = '''
{
"default": {
"engine": "postgresql",
"host": "localhost",
"port": 5432,
"credentials": {
"username": "user",
"password": "secret"
}
}
}
'''
db_config = env.json("DATABASE_CONFIG")
# => Complex nested dictionary structure
# Default JSON value
default_config = env.json("MISSING_CONFIG", {"enabled": False}) # => {"enabled": False}import os
from environs import env
from decimal import Decimal
# List of decimals for financial calculations
os.environ["PRICES"] = "19.99,29.99,49.99"
prices = env.list("PRICES", subcast=Decimal) # => [Decimal('19.99'), Decimal('29.99'), Decimal('49.99')]
# List of booleans
os.environ["FEATURE_FLAGS"] = "true,false,true"
flags = env.list("FEATURE_FLAGS", subcast=env.bool) # Custom subcast using env methodsimport os
from environs import env
# Multi-level configuration parsing
os.environ["CACHE_SETTINGS"] = "redis_host=localhost,redis_port=6379,redis_db=0,timeout=300"
cache_config = env.dict("CACHE_SETTINGS")
# Extract and cast specific values
redis_port = int(cache_config["redis_port"]) # Manual casting after parsing
timeout = int(cache_config["timeout"])from environs import env, EnvValidationError
import os
# Invalid JSON handling
os.environ["INVALID_JSON"] = '{"missing": "quote}'
try:
config = env.json("INVALID_JSON")
except EnvValidationError as e:
print(f"JSON parsing failed: {e}")
print(f"Error details: {e.error_messages}")
# Invalid list subcast handling
os.environ["INVALID_NUMBERS"] = "1,2,not_a_number,4"
try:
numbers = env.list("INVALID_NUMBERS", subcast=int)
except EnvValidationError as e:
print(f"List subcast failed: {e}")from typing import Any, Callable, Dict, List, Union
SubcastFunction = Union[type, Callable[[Any], Any]]
JSONValue = Union[Dict, List, str, int, float, bool, None]Install with Tessl CLI
npx tessl i tessl/pypi-environs