or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-data.mdconfiguration.mdcore-parsing.mdcustom-parsers.mdfile-secrets.mdframework-integration.mdindex.mdspecialized-types.mdvalidation.md
tile.json

tessl/pypi-environs

Simplified environment variable parsing with type casting, validation, and framework integration

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/environs@14.3.x

To install, run

npx @tessl/cli install tessl/pypi-environs@14.3.0

index.mddocs/

Environs

A Python library for parsing environment variables with type casting, validation, and framework integration. Environs allows you to store configuration separate from your code, following the Twelve-Factor App methodology, with comprehensive type support and validation capabilities.

Package Information

  • Package Name: environs
  • Language: Python
  • Installation: pip install environs

Core Imports

from environs import Env

Convenience import for the singleton instance:

from environs import env

For validation and exception handling:

from environs import validate, ValidationError, EnvError, EnvValidationError

Basic Usage

from environs import env
import os

# Set some environment variables
os.environ["API_KEY"] = "secret123"
os.environ["MAX_CONNECTIONS"] = "100"
os.environ["ENABLE_FEATURE"] = "true"
os.environ["COORDINATES"] = "23.3,50.0"

# Read .env file if it exists
env.read_env()

# Parse environment variables with type casting
api_key = env.str("API_KEY")  # => "secret123"
max_connections = env.int("MAX_CONNECTIONS")  # => 100
enable_feature = env.bool("ENABLE_FEATURE")  # => True

# Provide default values
timeout = env.int("TIMEOUT", 30)  # => 30 (default)

# Parse lists with type casting
coords = env.list("COORDINATES", subcast=float)  # => [23.3, 50.0]

Architecture

Environs provides two main classes and a comprehensive type system:

  • Env: Main environment variable reader with lazy validation
  • FileAwareEnv: Extended reader supporting Docker-style secret files
  • Type System: Built-in parsers for all common Python types plus custom parser registration
  • Validation: Marshmallow-powered validation with deferred error collection
  • Framework Integration: Specialized parsers for Django URL configurations

The library uses marshmallow fields internally for validation and type conversion, enabling consistent error handling and extensive customization capabilities.

Capabilities

Core Environment Parsing

Basic type parsing including strings, integers, booleans, floats, and raw values. These fundamental parsers handle the most common environment variable use cases with optional default values and validation.

def __call__(name: str, default=..., subcast=None, *, validate=None, **kwargs): ...
def str(name: str, default=..., *, validate=None, **kwargs): ...
def int(name: str, default=..., *, validate=None, **kwargs): ...
def bool(name: str, default=..., *, validate=None, **kwargs): ...
def float(name: str, default=..., *, validate=None, **kwargs): ...
def decimal(name: str, default=..., *, validate=None, **kwargs): ...

Core Parsing

Advanced Data Structures

Parsing of complex data structures including lists, dictionaries, and JSON with support for nested type casting and custom delimiters.

def list(name: str, default=..., subcast=None, *, delimiter=",", validate=None, **kwargs): ...
def dict(name: str, default=..., *, subcast_keys=None, subcast_values=None, 
         delimiter=",", key_value_delimiter="=", validate=None, **kwargs): ...
def json(name: str, default=..., *, validate=None, **kwargs): ...

Advanced Data Structures

Date, Time, and Specialized Types

Parsing of temporal types, paths, UUIDs, URLs, enums, and logging levels with format validation and conversion.

def datetime(name: str, default=..., *, validate=None, **kwargs): ...
def date(name: str, default=..., *, validate=None, **kwargs): ...
def time(name: str, default=..., *, validate=None, **kwargs): ...
def timedelta(name: str, default=..., *, validate=None, **kwargs): ...
def path(name: str, default=..., *, validate=None, **kwargs): ...
def uuid(name: str, default=..., *, validate=None, **kwargs): ...
def url(name: str, default=..., *, validate=None, **kwargs): ...
def log_level(name: str, default=..., *, validate=None, **kwargs): ...
def enum(name: str, default=..., *, enum, by_value=False, validate=None, **kwargs): ...

Specialized Types

Configuration Management

Environment configuration utilities including .env file reading, variable expansion, prefixed parsing, and validation management.

@staticmethod
def read_env(path=None, recurse=True, verbose=False, override=False, return_path=False): ...
def prefixed(prefix: str): ...
def seal(): ...
def dump(): ...

Configuration Management

Validation

Comprehensive validation support using marshmallow validators to ensure environment variables meet specific criteria with custom validation functions and error handling.

validate.OneOf(choices): ...     # Choice validation
validate.Range(min, max): ...    # Numeric range validation  
validate.Length(min, max): ...   # String/list length validation
validate.Email(): ...            # Email format validation
validate.URL(): ...              # URL format validation

Validation

Custom Parsers

Registration and management of custom parsing methods with marshmallow field integration and parser customization.

def add_parser(name: str, func: Callable): ...
def parser_for(name: str): ...
def add_parser_from_field(name: str, field_cls: Type[Field]): ...

Custom Parsers

Framework Integration

Specialized parsers for Django framework integration including database URLs, email configuration, and cache settings.

def dj_db_url(name: str, default=..., **kwargs): ...  # Returns: dict
def dj_email_url(name: str, default=..., **kwargs): ...  # Returns: dict
def dj_cache_url(name: str, default=..., **kwargs): ...  # Returns: dict

Framework Integration

File-Based Secrets

Docker-style secret file support for reading sensitive configuration from mounted files instead of environment variables.

class FileAwareEnv(Env):
    def __init__(self, file_suffix="_FILE", **kwargs): ...

File Secrets

Core Types

class Env:
    def __init__(self, eager: bool = True, expand_vars: bool = False, 
                 prefix: str | None = None): ...

class FileAwareEnv(Env):
    def __init__(self, file_suffix: str = "_FILE", eager: bool = True,
                 expand_vars: bool = False, prefix: str | None = None): ...

class EnvError(ValueError): ...

class EnvValidationError(EnvError):
    def __init__(self, message: str, error_messages): ...
    error_messages: dict | list

class EnvSealedError(TypeError, EnvError): ...

class ParserConflictError(ValueError): ...

# Re-exported from marshmallow
class ValidationError(Exception): ...

# Validation functions (re-exported from marshmallow.validate)
validate: module  # Contains validation functions like OneOf, Range, Email, etc.

Global Instance

env: Env  # Singleton instance for convenience