Python data validation library for validating nested data structures with comprehensive error reporting
npx @tessl/cli install tessl/pypi-voluptuous@0.15.0A Python data validation library designed for validating data coming into Python applications as JSON, YAML, and other formats. Voluptuous provides schema-based validation with support for complex nested data structures, comprehensive error reporting, and flexible validation composition.
pip install voluptuousimport voluptuousCommon patterns for schema validation:
from voluptuous import Schema, Required, Optional, All, Any, CoerceFor specific validators:
from voluptuous import Range, Length, Email, Url, Match, BooleanFor error handling:
from voluptuous import Invalid, MultipleInvalid, SchemaErrorfrom voluptuous import Schema, Required, Optional, All, Any, Range, Length, Email
# Define a schema for user data
user_schema = Schema({
Required('name'): All(str, Length(min=1, max=100)),
Required('email'): Email(),
Required('age'): All(int, Range(min=0, max=150)),
Optional('website'): Any(None, Url()),
Optional('tags', default=[]): [str],
})
# Validate data
user_data = {
'name': 'John Doe',
'email': 'john@example.com',
'age': 30,
'website': 'https://johndoe.com'
}
try:
validated_data = user_schema(user_data)
print(validated_data)
except Invalid as e:
print(f"Validation error: {e}")Voluptuous uses a composable validation system with three key concepts:
This design enables complex validation rules through simple composition, supports nested data structures, provides detailed error reporting with path information, and allows custom validation logic integration.
The foundational schema system for defining validation rules, handling required/optional fields, managing extra keys, and composing complex validation logic.
class Schema:
def __init__(self, schema, required=False, extra=PREVENT_EXTRA): ...
def __call__(self, data): ...
def extend(self, schema, required=None, extra=None): ...
@classmethod
def infer(cls, data, **kwargs): ...
class Required:
def __init__(self, schema, msg=None, default=UNDEFINED, description=None): ...
class Optional:
def __init__(self, schema, msg=None, default=UNDEFINED, description=None): ...
class Exclusive:
def __init__(self, schema, group_of_exclusion, msg=None, description=None): ...
class Inclusive:
def __init__(self, schema, group_of_inclusion, msg=None, description=None, default=UNDEFINED): ...Logical composition of multiple validators using boolean-like operations (Any/Or, All/And), union types with discriminants, and flexible validation count requirements.
class Any:
def __init__(self, *validators, msg=None, required=False, discriminant=None): ...
class All:
def __init__(self, *validators, msg=None, required=False, discriminant=None): ...
class Union:
def __init__(self, *validators, msg=None, discriminant=None): ...
class SomeOf:
def __init__(self, validators, min_valid=None, max_valid=None): ...Type conversion and coercion with error handling, truth value validation, and human-readable boolean conversion.
class Coerce:
def __init__(self, type, msg=None): ...
def Boolean(v): ...
def IsTrue(v): ...
def IsFalse(v): ...
def truth(f): ...Regular expression matching, string replacement, email and URL validation, file system path validation, and date/time format validation.
class Match:
def __init__(self, pattern, msg=None): ...
class Replace:
def __init__(self, pattern, substitution, msg=None): ...
def Email(v): ...
def Url(v): ...
def FqdnUrl(v): ...
def IsFile(v): ...
def IsDir(v): ...
def PathExists(v): ...
class Datetime:
def __init__(self, format=None, msg=None): ...
class Date:
def __init__(self, format=None, msg=None): ...Numeric range validation, sequence length validation, membership testing, numeric precision validation, exact value matching, and complex sequence validation patterns.
class Range:
def __init__(self, min=None, max=None, min_included=True, max_included=True, msg=None): ...
class Length:
def __init__(self, min=None, max=None, msg=None): ...
class In:
def __init__(self, container, msg=None): ...
class Contains:
def __init__(self, item, msg=None): ...
class ExactSequence:
def __init__(self, validators, msg=None): ...
class Equal:
def __init__(self, target, msg=None): ...
class Number:
def __init__(self, precision=None, scale=None, msg=None, yield_decimal=False): ...String transformation utilities, default value handling, value setting, and collection conversion utilities.
def Lower(v): ...
def Upper(v): ...
def Capitalize(v): ...
def Title(v): ...
def Strip(v): ...
class DefaultTo:
def __init__(self, default_value, msg=None): ...
class SetTo:
def __init__(self, value): ...
class Set:
def __init__(self, msg=None): ...Comprehensive exception hierarchy for validation errors with path tracking, multiple error aggregation, and detailed error reporting.
class Invalid(Exception):
def __init__(self, message, path=None, error_message=None, error_type=None): ...
@property
def msg(self): ...
@property
def path(self): ...
def prepend(self, path): ...
class MultipleInvalid(Invalid):
def __init__(self, errors=None): ...
def add(self, error): ...PREVENT_EXTRA = 0 # Disallow extra keys not in schema
ALLOW_EXTRA = 1 # Include extra keys in output
REMOVE_EXTRA = 2 # Exclude extra keys from output
UNDEFINED = Undefined() # Sentinel for undefined valuesSchemable = Union[
Schema, Object,
collections.abc.Mapping,
list, tuple, frozenset, set,
bool, bytes, int, str, float, complex,
type, object, dict, None, Callable
]
DefaultFactory = Union[Undefined, Callable[[], Any]]