Lightweight, extensible schema and data validation tool for Python dictionaries.
npx @tessl/cli install tessl/pypi-cerberus@1.3.0Cerberus is a lightweight, extensible schema and data validation tool for Python dictionaries. It provides comprehensive validation capabilities including type checking, value constraints, custom validation rules, and document normalization with zero dependencies (except for Python <3.8 compatibility).
pip install cerberusfrom cerberus import ValidatorCommon pattern for basic validation:
from cerberus import Validator, DocumentError, SchemaErrorAdvanced imports for custom types and error handling:
from cerberus import (
Validator,
TypeDefinition,
schema_registry,
rules_set_registry
)For error handling and tree navigation:
from cerberus.errors import (
ValidationError,
ErrorList,
ErrorTree,
DocumentErrorTree,
SchemaErrorTree,
BasicErrorHandler,
ToyErrorHandler,
SchemaErrorHandler
)For schema management and registries:
from cerberus.schema import (
DefinitionSchema,
Registry,
SchemaRegistry,
RulesSetRegistry
)For advanced customization:
from cerberus.utils import validator_factory, readonly_classpropertyfrom cerberus import Validator
# Simple validation with inline schema
schema = {'name': {'type': 'string'}, 'age': {'type': 'integer'}}
v = Validator(schema)
document = {'name': 'john', 'age': 30}
result = v.validate(document) # True
print(v.errors) # {} if valid
# Invalid document
invalid_doc = {'name': 123, 'age': 'thirty'}
v.validate(invalid_doc) # False
print(v.errors) # {'name': ['must be of string type'], 'age': ['must be of integer type']}
# Normalization and validation
normalized_doc = v.normalized(document)
print(normalized_doc) # Normalized version of documentCerberus uses a flexible validation architecture built around several key components:
The library's design emphasizes extensibility through custom validators, type definitions, error handlers, and schema registries, making it suitable for both simple validation tasks and complex, domain-specific validation requirements.
Primary validation functionality using the Validator class for document validation, normalization, and error handling. Supports comprehensive validation rules, custom constraints, and flexible validation modes.
class Validator:
def __init__(self, schema=None, ignore_none_values=False, allow_unknown=False,
require_all=False, purge_unknown=False, purge_readonly=False,
error_handler=None): ...
def validate(self, document, schema=None, update=False, normalize=True) -> bool: ...
def validated(self, *args, **kwargs): ...
def normalized(self, document, schema=None, always_return_document=False): ...Schema definition, validation, and storage system including registries for reusable schemas and rule sets. Provides structured schema validation and extensible schema definitions.
class DefinitionSchema:
def __init__(self, validator, schema): ...
def validate(self, schema=None): ...
def update(self, schema): ...
class Registry:
def add(self, name, definition): ...
def get(self, name, default=None): ...
def extend(self, definitions): ...Comprehensive error representation, organization, and formatting system with customizable error handlers and detailed validation feedback.
class ValidationError:
document_path: tuple
schema_path: tuple
code: int
rule: str
constraint: Any
value: Any
class BaseErrorHandler:
def __call__(self, errors): ...
def add(self, error): ...
def extend(self, errors): ...Custom type definition system for extending validation capabilities with domain-specific types and validation logic.
TypeDefinition = namedtuple('TypeDefinition', 'name,included_types,excluded_types')
def validator_factory(name, bases=None, namespace={}): ...Advanced validation capabilities including normalization, custom validators, field dependencies, and complex validation scenarios.
class Validator:
@property
def types_mapping(self): ...
@property
def validators(self): ...
@property
def coercers(self): ...
@property
def default_setters(self): ...schema_registry: SchemaRegistry
rules_set_registry: RulesSetRegistryThese global instances allow storing and retrieving schemas and rule sets by name throughout your application.
__version__: strThe current version of the Cerberus package.
class DocumentError(Exception): ...
class SchemaError(Exception): ...Primary exceptions for document format issues and schema definition problems.