API Documentation

Validator Class

class cerberus.Validator(schema: Union[ValidatedSchema, Mapping[Hashable, Mapping[str, Any]]] = None, *, allow_unknown: Union[bool, Mapping[str, Any]] = False, error_handler: Union[BaseErrorHandler, Type[BaseErrorHandler], Tuple[Type[BaseErrorHandler], Mapping[str, Any]]] = <class 'cerberus.errors.BasicErrorHandler'>, ignore_none_values: bool = False, purge_unknown: bool = False, purge_readonly: bool = False, require_all: bool = False, rules_set_registry: cerberus.base.RulesSetRegistry = <cerberus.base.RulesSetRegistry object>, schema_registry: cerberus.base.SchemaRegistry = <cerberus.base.SchemaRegistry object>, **extra_config)

Bases: cerberus.base.UnconcernedValidator

Validator class. Normalizes and/or validates any mapping against a validation-schema which is provided as an argument at class instantiation or upon calling the validate(), validated() or normalized() method. An instance itself is callable and executes a validation.

All instantiation parameters are optional.

There are the introspective properties types, validators, coercers, default_setters, rules, normalization_rules and validation_rules.

The attributes reflecting the available rules are assembled considering constraints that are defined in the docstrings of rules’ methods and is effectively used as validation schema for schema.

Parameters:
  • schema – See schema. Defaults to None.
  • ignore_none_values – See ignore_none_values. Defaults to False.
  • allow_unknown – See allow_unknown. Defaults to False.
  • require_all – See require_all. Defaults to False.
  • purge_unknown – See purge_unknown. Defaults to to False.
  • purge_readonly – Removes all fields that are defined as readonly in the normalization phase.
  • error_handler – The error handler that formats the result of errors. When given as two-value tuple with an error-handler class and a dictionary, the latter is passed to the initialization of the error handler. Default: BasicErrorHandler.
allow_unknown

If True unknown fields that are not defined in the schema will be ignored. If a mapping with a validation schema is given, any undefined field will be validated against its rules. Also see Allowing the Unknown.

Type: bool or any mapping

classmethod clear_caches()

Purge the cache of known valid schemas.

errors

The errors of the last processing formatted by the handler that is bound to error_handler.

ignore_none_values

Whether to not process None-values in a document or not.

Type: bool

is_child

True for child-validators obtained with _get_child_validator().

Type: bool

normalized(document: Mapping[Hashable, Any], schema: Union[ValidatedSchema, Mapping[Hashable, Mapping[str, Any]], None] = None, always_return_document: bool = False) → Optional[Mapping[Hashable, Any]]

Returns the document normalized according to the specified rules of a schema.

Parameters:
  • document – The document to normalize.
  • schema – The validation schema. Defaults to None. If not provided here, the schema must have been provided at class instantiation.
  • always_return_document – Return the document, even if an error occurred. Defaults to: False.
Returns:

A normalized copy of the provided mapping or None if an error occurred during normalization.

purge_readonly

If True, fields declared as readonly will be deleted from the document unless a validation is called with disabled normalization.

Type: bool

purge_unknown

If True, unknown fields will be deleted from the document unless a validation is called with disabled normalization. Also see Purging Unknown Fields.

Type: bool

require_all

If True known fields that are defined in the schema will be required.

Type: bool

root_allow_unknown

The allow_unknown attribute of the first level ancestor of a child validator.

root_document

The document attribute of the first level ancestor of a child validator.

root_require_all

The require_all attribute of the first level ancestor of a child validator.

root_schema

The schema attribute of the first level ancestor of a child validator.

rules_set_registry

The registry that holds referenced rules sets.

Type: Registry

schema

The validation schema of a validator. When a schema is passed to a validator method (e.g. validate), it replaces this attribute.

Type: any mapping or None

schema_registry

The registry that holds referenced schemas.

Type: Registry

validate(document: Mapping[Hashable, Any], schema: Union[ValidatedSchema, Mapping[Hashable, Mapping[str, Any]], None] = None, update: bool = False, normalize: bool = True) → bool

Normalizes and validates a mapping against a validation-schema of defined rules.

Parameters:
  • document – The document to normalize.
  • schema – The validation schema. Defaults to None. If not provided here, the schema must have been provided at class instantiation.
  • update – If True, required fields won’t be checked.
  • normalize – If True, normalize the document before validation.
Returns:

True if validation succeeds, otherwise False. Check the errors() property for a list of processing errors.

validated(document: Mapping[Hashable, Any], schema: Union[ValidatedSchema, Mapping[Hashable, Mapping[str, Any]], None] = None, update: bool = False, normalize: bool = True, always_return_document: bool = False) → Optional[Mapping[Hashable, Any]]

Wrapper around validate() that returns the normalized and validated document or None if validation failed.

Rules Set & Schema Registry

class cerberus.base.Registry(definitions: Union[Mapping[str, RegistryItem], Iterable[Tuple[str, RegistryItem]]] = ())

A registry to store and retrieve schemas and parts of it by a name that can be used in validation schemas.

Parameters:definitions – Optional, initial definitions.
add(name: str, definition: RegistryItem) → None

Register a definition to the registry. Existing definitions are replaced silently.

Parameters:
  • name – The name which can be used as reference in a validation schema.
  • definition – The definition.
all() → Mapping[str, RegistryItem]

Returns a dict with all registered definitions mapped to their name.

clear()

Purge all definitions in the registry.

extend(definitions: Union[Mapping[str, RegistryItem], Iterable[Tuple[str, RegistryItem]]]) → None

Add several definitions at once. Existing definitions are replaced silently.

Parameters:definitions – The names and definitions.
get(name: str, default: Optional[RegistryItem] = None) → Optional[RegistryItem]

Retrieve a definition from the registry.

Parameters:
  • name – The reference that points to the definition.
  • default – Return value if the reference isn’t registered.
remove(*names) → None

Unregister definitions from the registry.

Parameters:names – The names of the definitions that are to be unregistered.
class cerberus.schema.RulesSetRegistry(definitions: Union[Mapping[str, RegistryItem], Iterable[Tuple[str, RegistryItem]]] = ())

Bases: cerberus.base.Registry

class cerberus.schema.SchemaRegistry(definitions: Union[Mapping[str, RegistryItem], Iterable[Tuple[str, RegistryItem]]] = ())

Bases: cerberus.base.Registry

Type Definitions

class cerberus.TypeDefinition(name, included_types, excluded_types)

This class is used to define types that can be used as value in the types_mapping property. The name should be descriptive and match the key it is going to be assigned to. A value that is validated against such definition must be an instance of any of the types contained in included_types and must not match any of the types contained in excluded_types.

Error Handlers

class cerberus.errors.BaseErrorHandler(*args, **kwargs)

Base class for all error handlers.

__call__(errors: Iterable[cerberus.errors.ValidationError]) → Any

Returns errors in a handler-specific format.

__init__(*args, **kwargs)

Optionally initialize a new instance.

__iter__() → Iterator[Any]

Be a superhero and implement an iterator over errors.

__weakref__

list of weak references to the object (if defined)

add(error: cerberus.errors.ValidationError) → None

Add an error to the errors’ container object of a handler.

Parameters:error – The error to add.
emit(error: cerberus.errors.ValidationError) → None

Optionally emits an error in the handler’s format to a stream. Or light a LED, or even shut down a power plant.

Parameters:error – The error to emit.
end(validator: UnconcernedValidator) → None

Gets called when a validation ends.

Parameters:validator – The calling validator.
extend(errors: Iterable[cerberus.errors.ValidationError]) → None

Adds all errors to the handler’s container object.

start(validator: UnconcernedValidator) → None

Gets called when a validation starts.

Parameters:validator – The calling validator.
class cerberus.errors.BasicErrorHandler(tree: Dict[KT, VT] = None)

Bases: cerberus.errors.BaseErrorHandler

Models cerberus’ legacy. Returns a dict. When mangled through str a pretty-formatted representation of that tree is returned.

Python Error Representations

class cerberus.errors.ErrorDefinition(code: int, rule: Optional[str])

This class is used to define possible errors. Each distinguishable error is defined by a unique error code as integer and the rule that can cause it as string. The instances’ names do not contain a common prefix as they are supposed to be referenced within the module namespace, e.g. errors.CUSTOM.

class cerberus.errors.ValidationError(document_path: Tuple[Hashable, ...], schema_path: Tuple[Hashable, ...], code: int, rule: str, constraint: Any, value: Any, info: Any)

A simple class to store and query basic error information.

child_errors

A list that contains the individual errors of a bulk validation error.

code = None

The error’s identifier code. Type: int

constraint = None

The constraint that failed.

definitions_errors

Dictionary with errors of an *of-rule mapped to the index of the definition it occurred in. Returns None if not applicable.

document_path = None

The path to the field within the document that caused the error. Type: tuple

field

Field of the contextual mapping, possibly None.

info = None

May hold additional information about the error. Type: tuple

is_group_error

True for errors of bulk validations.

is_logic_error

True for validation errors against different schemas with *of-rules.

is_normalization_error

True for normalization errors.

rule = None

The rule that failed. Type: string

schema_path = None

The path to the rule within the schema that caused the error. Type: tuple

value = None

The value that failed.

Error Codes

Its code attribute uniquely identifies an ErrorDefinition that is used a concrete error’s code. Some codes are actually reserved to mark a shared property of different errors. These are useful as bitmasks while processing errors. This is the list of the reserved codes:

0110 0000 0x60 96 An error that occurred during normalization.
1000 0000 0x80 128 An error that contains child errors.
1001 0000 0x90 144 An error that was emitted by one of the *of-rules.

None of these bits in the upper nibble must be used to enumerate error definitions, but only to mark one with the associated property.

Important

Users are advised to set bit 8 for self-defined errors. So the code 0001 0000 0001 / 0x101 would the first in a domain-specific set of error definitions.

This is a list of all error defintions that are shipped with the errors module:

Code (dec.) Code (hex.) Name Rule
0 0x0 CUSTOM None
2 0x2 REQUIRED_FIELD required
3 0x3 UNKNOWN_FIELD None
4 0x4 DEPENDENCIES_FIELD dependencies
5 0x5 DEPENDENCIES_FIELD_VALUE dependencies
6 0x6 EXCLUDES_FIELD excludes
34 0x22 EMPTY empty
35 0x23 NULLABLE nullable
36 0x24 TYPE type
38 0x26 ITEMS_LENGTH items
39 0x27 MIN_LENGTH minlength
40 0x28 MAX_LENGTH maxlength
65 0x41 REGEX_MISMATCH regex
66 0x42 MIN_VALUE min
67 0x43 MAX_VALUE max
68 0x44 UNALLOWED_VALUE allowed
69 0x45 UNALLOWED_VALUES allowed
70 0x46 FORBIDDEN_VALUE forbidden
71 0x47 FORBIDDEN_VALUES forbidden
72 0x48 MISSING_MEMBERS contains
96 0x60 NORMALIZATION None
97 0x61 COERCION_FAILED coerce
98 0x62 RENAMING_FAILED rename_handler
99 0x63 READONLY_FIELD readonly
100 0x64 SETTING_DEFAULT_FAILED default_setter
128 0x80 ERROR_GROUP None
129 0x81 SCHEMA schema
130 0x82 ITEMSRULES itemsrules
131 0x83 KEYSRULES keysrules
132 0x84 VALUESRULES valuesrules
143 0x8f ITEMS items
144 0x90 LOGICAL None
145 0x91 NONEOF noneof
146 0x92 ONEOF oneof
147 0x93 ANYOF anyof
148 0x94 ALLOF allof

Error Containers

class cerberus.errors.ErrorList

A list for ValidationError instances that can be queried with the in keyword for a particular ErrorDefinition.

class cerberus.errors.ErrorTree(errors: Iterable[cerberus.errors.ValidationError] = ())

Base class for DocumentErrorTree and SchemaErrorTree.

add(error: cerberus.errors.ValidationError) → None

Add an error to the tree.

fetch_errors_from(path: Tuple[Hashable, ...]) → cerberus.errors.ErrorList

Returns all errors for a particular path.

fetch_node_from(path: Tuple[Hashable, ...]) → cerberus.errors.ErrorTreeNode

Returns a node for a path.

class cerberus.errors.DocumentErrorTree(errors: Iterable[cerberus.errors.ValidationError] = ())

Bases: cerberus.errors.ErrorTree

Implements a dict-like class to query errors by indexes following the structure of a validated document.

class cerberus.errors.SchemaErrorTree(errors: Iterable[cerberus.errors.ValidationError] = ())

Bases: cerberus.errors.ErrorTree

Implements a dict-like class to query errors by indexes following the structure of the used schema.

Exceptions

exception cerberus.SchemaError

Raised when the validation schema is missing, has the wrong format or contains errors.

exception cerberus.DocumentError

Raised when the target document is missing or has the wrong format

Utilities

cerberus.validator_factory(name: str, bases: Union[type, Tuple[type], None] = None, namespace: Optional[Dict[KT, VT]] = None, validated_schema: bool = True) → type

Dynamically create a Validator subclass. Docstrings of mixin-classes will be added to the resulting class’ one if __doc__ is not in namespace.

Parameters:
  • name – The name of the new class.
  • bases – Class(es) with additional and overriding attributes.
  • namespace – Attributes for the new class.
  • validated_schema – Indicates that schemas that are provided to the validator are to be validated.
Returns:

The created class.

Schema Validation Schema

Against this schema validation schemas given to a vanilla Validator will be validated:

ChainMap({'coerce': {'oneof': ({'type': ('Callable',)},
                              {'itemsrules': {'oneof': ({'type': ('Callable',)},
                                                        {'allowed': (),
                                                         'type': ('string',)})},
                               'type': ('Iterable',)},
                              {'allowed': (),
                               'type': ('string',)})},
         'default': {'nullable': True},
         'default_setter': {'oneof': ({'type': ('Callable',)},
                                      {'allowed': (),
                                       'type': ('string',)})},
         'purge_unknown': {'type': ('boolean',)},
         'rename': {'type': ('Hashable',)},
         'rename_handler': {'oneof': ({'type': ('Callable',)},
                                      {'itemsrules': {'oneof': ({'type': ('Callable',)},
                                                                {'allowed': (),
                                                                 'type': ('string',)})},
                                       'type': ('Iterable',)},
                                      {'allowed': (),
                                       'type': ('string',)})}},
        {'allof': {'logical': 'allof', 'type': ('Sequence',)},
         'allow_unknown': {'oneof': ({'type': ('boolean',)},
                                     {'check_with': 'rulesset',
                                      'type': ('dict',
                                               'string')})},
         'allowed': {'type': ('container_but_not_string',)},
         'anyof': {'logical': 'anyof', 'type': ('Sequence',)},
         'check_with': {'oneof': ({'type': ('Callable',)},
                                  {'itemsrules': {'oneof': ({'type': ('Callable',)},
                                                            {'allowed': (),
                                                             'type': ('string',)})},
                                   'type': ('Iterable',)},
                                  {'allowed': (),
                                   'type': ('string',)})},
         'contains': {'empty': False},
         'dependencies': {'check_with': 'dependencies',
                          'type': ('Hashable',
                                   'Iterable',
                                   'Mapping')},
         'empty': {'type': ('boolean',)},
         'excludes': {'itemsrules': {'type': ('Hashable',)},
                      'type': ('Hashable', 'Iterable')},
         'forbidden': {'type': ('Container',)},
         'items': {'check_with': 'items', 'type': ('Sequence',)},
         'itemsrules': {'check_with': 'rulesset',
                        'type': ('dict', 'string')},
         'keysrules': {'check_with': 'rulesset',
                       'forbidden': ('rename', 'rename_handler'),
                       'type': ('Mapping', 'string')},
         'max': {'nullable': False},
         'maxlength': {'type': ('integer',)},
         'meta': {},
         'min': {'nullable': False},
         'minlength': {'type': ('integer',)},
         'noneof': {'logical': 'noneof', 'type': ('Sequence',)},
         'nullable': {'type': ('boolean',)},
         'oneof': {'logical': 'oneof', 'type': ('Sequence',)},
         'readonly': {'type': ('boolean',)},
         'regex': {'type': ('string',)},
         'require_all': {'type': ('boolean',)},
         'required': {'type': ('boolean',)},
         'schema': {'check_with': 'schema',
                    'type': ('Mapping', 'string')},
         'type': {'itemsrules': {'oneof': ({'check_with': 'type_names',
                                            'type': ('string',)},
                                           {'type': ('type',
                                                     'generic_type_alias')})},
                  'type': ('tuple',)},
         'valuesrules': {'check_with': 'rulesset',
                         'forbidden': ['rename', 'rename_handler'],
                         'type': ('dict', 'string')}})