Simplified environment variable parsing with type casting, validation, and framework integration
—
Basic type parsing functionality that forms the foundation of environs' environment variable handling. These parsers handle the most common data types with automatic type conversion, optional default values, and validation support.
from environs import Env, env
from environs import validate, ValidationError, EnvError, EnvValidationErrorParses environment variables as raw strings without type conversion, providing the foundation for all other parsing methods.
def __call__(self, name: str, default=..., subcast=None, *, validate=None, **kwargs):
"""
Parse environment variable as raw value.
Parameters:
- name: str, environment variable name
- default: any, default value if variable not set (optional)
- subcast: type or callable for type conversion (optional)
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
Raw value from environment or default
"""Explicitly parse environment variables as strings with validation and processing options.
def str(self, name: str, default=..., *, validate=None, **kwargs):
"""
Parse environment variable as string.
Parameters:
- name: str, environment variable name
- default: str, default value if variable not set (optional)
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
str: String value from environment or default
"""Parse environment variables as integers with validation for numeric format and range constraints.
def int(self, name: str, default=..., *, validate=None, **kwargs):
"""
Parse environment variable as integer.
Parameters:
- name: str, environment variable name
- default: int, default value if variable not set (optional)
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
int: Integer value from environment or default
Raises:
EnvValidationError: If value cannot be converted to integer
"""Usage example:
import os
from environs import env
os.environ["PORT"] = "8080"
os.environ["MAX_WORKERS"] = "4"
port = env.int("PORT") # => 8080
max_workers = env.int("MAX_WORKERS", 1) # => 4
default_timeout = env.int("TIMEOUT", 30) # => 30 (default)Parse environment variables as booleans with support for common boolean representations.
def bool(self, name: str, default=..., *, validate=None, **kwargs):
"""
Parse environment variable as boolean.
Parameters:
- name: str, environment variable name
- default: bool, default value if variable not set (optional)
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
bool: Boolean value from environment or default
Notes:
Truthy values: 'true', 'True', 'TRUE', '1', 'yes', 'Yes', 'YES', 'on', 'On', 'ON'
Falsy values: 'false', 'False', 'FALSE', '0', 'no', 'No', 'NO', 'off', 'Off', 'OFF', ''
"""Usage example:
import os
from environs import env
os.environ["DEBUG"] = "true"
os.environ["ENABLE_CACHE"] = "false"
debug = env.bool("DEBUG") # => True
enable_cache = env.bool("ENABLE_CACHE") # => False
enable_logging = env.bool("ENABLE_LOGGING", True) # => True (default)Parse environment variables as floating-point numbers with precision handling.
def float(self, name: str, default=..., *, validate=None, **kwargs):
"""
Parse environment variable as float.
Parameters:
- name: str, environment variable name
- default: float, default value if variable not set (optional)
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
float: Float value from environment or default
Raises:
EnvValidationError: If value cannot be converted to float
"""Parse environment variables as high-precision decimal numbers using Python's decimal module.
def decimal(self, name: str, default=..., *, validate=None, **kwargs):
"""
Parse environment variable as Decimal.
Parameters:
- name: str, environment variable name
- default: Decimal, default value if variable not set (optional)
- validate: callable or list of callables for validation (optional)
- **kwargs: additional marshmallow field arguments
Returns:
decimal.Decimal: High-precision decimal value from environment or default
Raises:
EnvValidationError: If value cannot be converted to Decimal
"""Usage example:
import os
from environs import env
from decimal import Decimal
os.environ["PRICE"] = "19.99"
os.environ["PI"] = "3.141592653589793238462643383279"
price = env.decimal("PRICE") # => Decimal('19.99')
pi = env.decimal("PI") # => Decimal('3.141592653589793238462643383279')
default_rate = env.decimal("TAX_RATE", Decimal("0.08")) # => Decimal('0.08') (default)All parsing methods can raise validation errors when environment variables cannot be converted to the expected type:
from environs import env, EnvValidationError
import os
os.environ["INVALID_NUMBER"] = "not_a_number"
try:
value = env.int("INVALID_NUMBER")
except EnvValidationError as e:
print(f"Validation failed: {e}")
print(f"Error details: {e.error_messages}")All core parsing methods support these common parameters:
... for required variables)environs.validate)from decimal import Decimal
from typing import Any, Callable, Union
Subcast = Union[type, Callable[[Any], Any]]
ValidationFunction = Callable[[Any], Any]Install with Tessl CLI
npx tessl i tessl/pypi-environs