cattrs package¶
- class cattrs.AttributeValidationNote(string, name, type)[source]¶
Bases:
strAttached as a note to an exception when an attribute fails structuring.
- Parameters:
string (str)
name (str)
type (Any)
- Return type:
Self
- name: str¶
- type: Any¶
- class cattrs.BaseConverter(dict_factory=<class 'dict'>, unstruct_strat=UnstructureStrategy.AS_DICT, prefer_attrib_converters=False, detailed_validation=True, unstructure_fallback_factory=<function BaseConverter.<lambda>>, structure_fallback_factory=<function BaseConverter.<lambda>>)[source]¶
Bases:
objectConverts between structured and unstructured data.
- Parameters:
detailed_validation (bool) – Whether to use a slightly slower mode for detailed validation errors.
unstructure_fallback_factory (HookFactory[UnstructureHook]) – A hook factory to be called when no registered unstructuring hooks match.
structure_fallback_factory (HookFactory[StructureHook]) – A hook factory to be called when no registered structuring hooks match.
dict_factory (Callable[[], Any])
unstruct_strat (UnstructureStrategy)
prefer_attrib_converters (bool)
Added in version 23.2.0: unstructure_fallback_factory
Added in version 23.2.0: structure_fallback_factory
Changed in version 24.2.0: The default structure_fallback_factory now raises errors for missing handlers more eagerly, surfacing problems earlier.
- detailed_validation¶
- copy(dict_factory=None, unstruct_strat=None, prefer_attrib_converters=None, detailed_validation=None)[source]¶
Create a copy of the converter, keeping all existing custom hooks.
- Parameters:
detailed_validation (bool | None) – Whether to use a slightly slower mode for detailed validation errors.
dict_factory (Callable[[], Any] | None)
unstruct_strat (UnstructureStrategy | None)
prefer_attrib_converters (bool | None)
- Return type:
Self
- get_structure_hook(type, cache_result=True)[source]¶
Get the structure hook for the given type.
This hook can be manually called, or composed with other functions and re-registered.
If no hook is registered, the converter structure fallback factory will be used to produce one.
- Parameters:
cache – Whether to cache the returned hook.
type (Any)
cache_result (bool)
- Return type:
Callable[[Any, Any], Any]
Added in version 24.1.0.
- get_unstructure_hook(type, cache_result=True)[source]¶
Get the unstructure hook for the given type.
This hook can be manually called, or composed with other functions and re-registered.
If no hook is registered, the converter unstructure fallback factory will be used to produce one.
- Parameters:
cache – Whether to cache the returned hook.
type (Any)
cache_result (bool)
- Return type:
Callable[[Any], Any]
Added in version 24.1.0.
- register_structure_hook(cl, func=None)[source]¶
Register a primitive-to-class converter function for a type.
- The converter function should take two arguments:
a Python object to be converted,
the type to convert to
and return the instance of the class. The type may seem redundant, but is sometimes needed (for example, when dealing with generic classes).
This method may be used as a decorator. In this case, the decorated hook must have a return type annotation, and this annotation will be used as the type for the hook.
Changed in version 24.1.0: This method may now be used as a decorator.
Changed in version 25.1.0: Modern type aliases are now supported.
- Parameters:
cl (Any)
func (Callable[[Any, Any], Any] | None)
- Return type:
None
- register_structure_hook_factory(predicate, factory=None)[source]¶
Register a hook factory for a given predicate.
The hook factory may expose an additional required parameter. In this case, the current converter will be provided to the hook factory as that parameter.
May also be used as a decorator.
- Parameters:
predicate – A function that, given a type, returns whether the factory can produce a hook for that type.
factory – A callable that, given a type, produces a structuring hook for that type. This structuring hook will be cached.
Changed in version 24.1.0: This method may now be used as a decorator. The factory may also receive the converter as a second, required argument.
- register_structure_hook_func(check_func, func)[source]¶
Register a class-to-primitive converter function for a class, using a function to check if it’s a match.
- Parameters:
check_func (Callable[[Any], bool])
func (Callable[[Any, Any], Any])
- Return type:
None
- register_unstructure_hook(cls=None, func=None)[source]¶
Register a class-to-primitive converter function for a class.
The converter function should take an instance of the class and return its Python equivalent.
May also be used as a decorator. When used as a decorator, the first argument annotation from the decorated function will be used as the type to register the hook for.
Changed in version 24.1.0: This method may now be used as a decorator.
Changed in version 25.1.0: Modern type aliases are now supported.
- Parameters:
cls (Any)
func (UnstructureHook | None)
- Return type:
Callable[[UnstructureHook]] | None
- register_unstructure_hook_factory(predicate, factory=None)[source]¶
Register a hook factory for a given predicate.
The hook factory may expose an additional required parameter. In this case, the current converter will be provided to the hook factory as that parameter.
May also be used as a decorator.
- Parameters:
predicate – A function that, given a type, returns whether the factory can produce a hook for that type.
factory – A callable that, given a type, produces an unstructuring hook for that type. This unstructuring hook will be cached.
Changed in version 24.1.0: This method may now be used as a decorator. The factory may also receive the converter as a second, required argument.
- register_unstructure_hook_func(check_func, func)[source]¶
Register a class-to-primitive converter function for a class, using a function to check if it’s a match.
- Parameters:
check_func (Callable[[Any], bool])
func (Callable[[Any], Any])
- Return type:
None
- structure(obj, cl)[source]¶
Convert unstructured Python data structures to structured data.
- Parameters:
obj (Any)
cl (type[T])
- Return type:
T
- structure_attrs_fromdict(obj, cl)[source]¶
Instantiate an attrs class from a mapping (dict).
- Parameters:
obj (Mapping[str, Any])
cl (type[T])
- Return type:
T
- structure_attrs_fromtuple(obj, cl)[source]¶
Load an attrs class from a sequence (tuple).
- Parameters:
obj (tuple[Any, ...])
cl (type[T])
- Return type:
T
- property unstruct_strat: UnstructureStrategy¶
The default way of unstructuring
attrsclasses.
- unstructure(obj, unstructure_as=None)[source]¶
- Parameters:
obj (Any)
unstructure_as (Any)
- Return type:
Any
- exception cattrs.BaseValidationError(message, excs, cl)[source]¶
Bases:
ExceptionGroup,CattrsError- Parameters:
message (str)
excs (Sequence[Exception])
cl (type)
- Return type:
Self
- cl: type¶
- exception cattrs.ClassValidationError(message, excs, cl)[source]¶
Bases:
BaseValidationErrorRaised when validating a class if any attributes are invalid.
- Parameters:
message (str)
excs (Sequence[Exception])
cl (type)
- Return type:
Self
- group_exceptions()[source]¶
Split the exceptions into two groups: with and without validation notes.
- Return type:
tuple[list[tuple[Exception, AttributeValidationNote]], list[Exception]]
- class cattrs.Converter(dict_factory=<class 'dict'>, unstruct_strat=UnstructureStrategy.AS_DICT, omit_if_default=False, forbid_extra_keys=False, type_overrides={}, unstruct_collection_overrides={}, prefer_attrib_converters=False, detailed_validation=True, unstructure_fallback_factory=<function Converter.<lambda>>, structure_fallback_factory=<function Converter.<lambda>>, use_alias=False)[source]¶
Bases:
BaseConverterA converter which generates specialized un/structuring functions.
- Parameters:
detailed_validation (bool) – Whether to use a slightly slower mode for detailed validation errors.
unstructure_fallback_factory (HookFactory[UnstructureHook]) – A hook factory to be called when no registered unstructuring hooks match.
structure_fallback_factory (HookFactory[StructureHook]) – A hook factory to be called when no registered structuring hooks match.
use_alias (bool) – Whether to use the field alias instead of the field name as the un/structured dictionary key by default.
dict_factory (Callable[[], Any])
unstruct_strat (UnstructureStrategy)
omit_if_default (bool)
forbid_extra_keys (bool)
type_overrides (Mapping[type, AttributeOverride])
unstruct_collection_overrides (Mapping[type, UnstructureHook])
prefer_attrib_converters (bool)
Added in version 23.2.0: unstructure_fallback_factory
Added in version 23.2.0: structure_fallback_factory
Changed in version 24.2.0: The default structure_fallback_factory now raises errors for missing handlers more eagerly, surfacing problems earlier.
Added in version 25.2.0: use_alias
- forbid_extra_keys¶
- omit_if_default¶
- type_overrides¶
- use_alias¶
- copy(dict_factory=None, unstruct_strat=None, omit_if_default=None, forbid_extra_keys=None, type_overrides=None, unstruct_collection_overrides=None, prefer_attrib_converters=None, detailed_validation=None, use_alias=None)[source]¶
Create a copy of the converter, keeping all existing custom hooks.
- Parameters:
detailed_validation (bool | None) – Whether to use a slightly slower mode for detailed validation errors.
dict_factory (Callable[[], Any] | None)
unstruct_strat (UnstructureStrategy | None)
omit_if_default (bool | None)
forbid_extra_keys (bool | None)
type_overrides (Mapping[type, AttributeOverride] | None)
unstruct_collection_overrides (Mapping[type, Callable[[Any], Any]] | None)
prefer_attrib_converters (bool | None)
use_alias (bool | None)
- Return type:
Self
- gen_structure_attrs_fromdict(cl)[source]¶
- Parameters:
cl (type[T])
- Return type:
Callable[[Mapping[str, Any], Any], T]
- gen_structure_counter(cl)[source]¶
- Parameters:
cl (type[CounterT])
- Return type:
SimpleStructureHook[Mapping[Any, Any], CounterT]
- gen_structure_mapping(cl)[source]¶
- Parameters:
cl (Any)
- Return type:
SimpleStructureHook[Mapping[Any, Any], Any]
- gen_structure_typeddict(cl)[source]¶
Generate a TypedDict structure function.
Also apply converter-scored modifications.
- Parameters:
cl (Any)
- Return type:
Callable[[dict, Any], dict]
- gen_unstructure_attrs_fromdict(cl)[source]¶
- Parameters:
cl (type[T])
- Return type:
Callable[[T], dict[str, Any]]
- gen_unstructure_hetero_tuple(cl, unstructure_to=None)[source]¶
- Parameters:
cl (Any)
unstructure_to (Any)
- Return type:
Callable[[tuple[Any, …]], Any]
- gen_unstructure_iterable(cl, unstructure_to=None)[source]¶
- Parameters:
cl (Any)
unstructure_to (Any)
- Return type:
Callable[[Iterable[Any]], Any]
- gen_unstructure_mapping(cl, unstructure_to=None, key_handler=None)[source]¶
- Parameters:
cl (Any)
unstructure_to (Any)
key_handler (Callable[[Any, Any | None], Any] | None)
- Return type:
Callable[[Mapping[Any, Any]], Any]
- gen_unstructure_optional(cl)[source]¶
Generate an unstructuring hook for optional types.
- Parameters:
cl (type[T])
- Return type:
Callable[[T], Any]
- gen_unstructure_typeddict(cl)[source]¶
Generate a TypedDict unstructure function.
Also apply converter-scored modifications.
- Parameters:
cl (Any)
- Return type:
Callable[[dict], dict]
- get_structure_newtype(type)[source]¶
- Parameters:
type (type[T])
- Return type:
Callable[[Any, Any], T]
- register_structure_hook_factory(predicate, factory=None)[source]¶
Register a hook factory for a given predicate.
The hook factory may expose an additional required parameter. In this case, the current converter will be provided to the hook factory as that parameter.
May also be used as a decorator.
- Parameters:
predicate – A function that, given a type, returns whether the factory can produce a hook for that type.
factory – A callable that, given a type, produces a structuring hook for that type. This structuring hook will be cached.
Changed in version 24.1.0: This method may now be used as a decorator. The factory may also receive the converter as a second, required argument.
- register_unstructure_hook_factory(predicate, factory=None)[source]¶
Register a hook factory for a given predicate.
The hook factory may expose an additional required parameter. In this case, the current converter will be provided to the hook factory as that parameter.
May also be used as a decorator.
- Parameters:
predicate – A function that, given a type, returns whether the factory can produce a hook for that type.
factory – A callable that, given a type, produces an unstructuring hook for that type. This unstructuring hook will be cached.
Changed in version 24.1.0: This method may now be used as a decorator. The factory may also receive the converter as a second, required argument.
- exception cattrs.ForbiddenExtraKeysError(message, cl, extra_fields)[source]¶
Bases:
CattrsErrorRaised when forbid_extra_keys is activated and such extra keys are detected during structuring.
The attribute extra_fields is a sequence of those extra keys, which were the cause of this error, and cl is the class which was structured with those extra keys.
- Parameters:
message (str | None)
cl (type)
extra_fields (set[str])
- Return type:
None
- exception cattrs.IterableValidationError(message, excs, cl)[source]¶
Bases:
BaseValidationErrorRaised when structuring an iterable.
- Parameters:
message (str)
excs (Sequence[Exception])
cl (type)
- Return type:
Self
- group_exceptions()[source]¶
Split the exceptions into two groups: with and without validation notes.
- Return type:
tuple[list[tuple[Exception, IterableValidationNote]], list[Exception]]
- class cattrs.IterableValidationNote(string, index, type)[source]¶
Bases:
strAttached as a note to an exception when an iterable element fails structuring.
- Parameters:
string (str)
index (int | str)
type (Any)
- Return type:
Self
- type: Any¶
- class cattrs.SimpleStructureHook(*args, **kwargs)[source]¶
Bases:
Protocol[In,T]A structure hook with an optional (ignored) second argument.
- exception cattrs.StructureHandlerNotFoundError(message, type_)[source]¶
Bases:
CattrsErrorError raised when structuring cannot find a handler for converting inputs into
type_.- Parameters:
message (str)
type_ (type)
- Return type:
None
- class cattrs.UnstructureStrategy(*values)[source]¶
Bases:
Enumattrs classes unstructuring strategies.
- AS_DICT = 'asdict'¶
- AS_TUPLE = 'astuple'¶
- cattrs.get_structure_hook(type, cache_result=True)¶
Get the structure hook for the given type.
This hook can be manually called, or composed with other functions and re-registered.
If no hook is registered, the converter structure fallback factory will be used to produce one.
- Parameters:
cache – Whether to cache the returned hook.
type (Any)
cache_result (bool)
- Return type:
Callable[[Any, Any], Any]
Added in version 24.1.0.
- cattrs.get_unstructure_hook(type, cache_result=True)¶
Get the unstructure hook for the given type.
This hook can be manually called, or composed with other functions and re-registered.
If no hook is registered, the converter unstructure fallback factory will be used to produce one.
- Parameters:
cache – Whether to cache the returned hook.
type (Any)
cache_result (bool)
- Return type:
Callable[[Any], Any]
Added in version 24.1.0.
- cattrs.global_converter: Final = <cattrs.converters.Converter object>¶
The global converter. Prefer creating your own if customizations are required.
- cattrs.override(omit_if_default=None, rename=None, omit=None, struct_hook=None, unstruct_hook=None)[source]¶
Override how a particular field is handled.
- Parameters:
omit (bool | None) – Whether to skip the field or not. None means apply default handling.
omit_if_default (bool | None)
rename (str | None)
struct_hook (Callable[[Any, Any], Any] | None)
unstruct_hook (Callable[[Any], Any] | None)
- Return type:
AttributeOverride
- cattrs.register_structure_hook(cl, func=None)¶
Register a primitive-to-class converter function for a type.
- The converter function should take two arguments:
a Python object to be converted,
the type to convert to
and return the instance of the class. The type may seem redundant, but is sometimes needed (for example, when dealing with generic classes).
This method may be used as a decorator. In this case, the decorated hook must have a return type annotation, and this annotation will be used as the type for the hook.
Changed in version 24.1.0: This method may now be used as a decorator.
Changed in version 25.1.0: Modern type aliases are now supported.
- Parameters:
cl (Any)
func (Callable[[Any, Any], Any] | None)
- Return type:
None
- cattrs.register_structure_hook_func(check_func, func)¶
Register a class-to-primitive converter function for a class, using a function to check if it’s a match.
- Parameters:
check_func (Callable[[Any], bool])
func (Callable[[Any, Any], Any])
- Return type:
None
- cattrs.register_unstructure_hook(cls=None, func=None)¶
Register a class-to-primitive converter function for a class.
The converter function should take an instance of the class and return its Python equivalent.
May also be used as a decorator. When used as a decorator, the first argument annotation from the decorated function will be used as the type to register the hook for.
Changed in version 24.1.0: This method may now be used as a decorator.
Changed in version 25.1.0: Modern type aliases are now supported.
- Parameters:
cls (Any)
func (UnstructureHook | None)
- Return type:
Callable[[UnstructureHook]] | None
- cattrs.register_unstructure_hook_func(check_func, func)¶
Register a class-to-primitive converter function for a class, using a function to check if it’s a match.
- Parameters:
check_func (Callable[[Any], bool])
func (Callable[[Any], Any])
- Return type:
None
- cattrs.structure(obj, cl)¶
Convert unstructured Python data structures to structured data.
- Parameters:
obj (Any)
cl (type[T])
- Return type:
T
- cattrs.structure_attrs_fromdict(obj, cl)¶
Instantiate an attrs class from a mapping (dict).
- Parameters:
obj (Mapping[str, Any])
cl (type[T])
- Return type:
T
- cattrs.structure_attrs_fromtuple(obj, cl)¶
Load an attrs class from a sequence (tuple).
- Parameters:
obj (tuple[Any, ...])
cl (type[T])
- Return type:
T
- cattrs.transform_error(exc, path='$', format_exception=<function format_exception>)[source]¶
Transform an exception into a list of error messages.
To get detailed error messages, the exception should be produced by a converter with detailed_validation set.
By default, the error messages are in the form of {description} @ {path}.
While traversing the exception and subexceptions, the path is formed:
by appending .{field_name} for fields in classes
by appending [{int}] for indices in iterables, like lists
by appending [{str}] for keys in mappings, like dictionaries
- Parameters:
exc (ClassValidationError | IterableValidationError | BaseException) – The exception to transform into error messages.
path (str) – The root path to use.
format_exception (Callable[[BaseException, type | None], str]) – A callable to use to transform Exceptions into string descriptions of errors.
- Return type:
list[str]
Added in version 23.1.0.
- cattrs.unstructure(obj, unstructure_as=None)¶
- Parameters:
obj (Any)
unstructure_as (Any)
- Return type:
Any
Subpackages¶
- cattrs.gen package
- cattrs.preconf package
validate_datetime()wrap()is_primitive_enum()literals_with_enums_unstructure_factory()- Submodules
- cattrs.preconf.bson module
- cattrs.preconf.cbor2 module
- cattrs.preconf.json module
- cattrs.preconf.msgpack module
- cattrs.preconf.msgspec module
MsgspecJsonConverterMsgspecJsonConverter.encoderMsgspecJsonConverter.dumps()MsgspecJsonConverter.get_dumps_hook()MsgspecJsonConverter.loads()MsgspecJsonConverter.get_loads_hook()MsgspecJsonConverter.forbid_extra_keysMsgspecJsonConverter.omit_if_defaultMsgspecJsonConverter.type_overridesMsgspecJsonConverter.use_alias
configure_converter()make_converter()
- cattrs.preconf.orjson module
- cattrs.preconf.pyyaml module
- cattrs.preconf.tomlkit module
- cattrs.preconf.tomllib module
- cattrs.preconf.ujson module
- cattrs.strategies package
Submodules¶
cattrs.cols module¶
Utility functions for collections.
- cattrs.cols.defaultdict_structure_factory(type, converter, default_factory=NOTHING)[source]¶
A structure hook factory for defaultdicts.
The value type parameter will be used as the _default factory_.
- Parameters:
type (type[defaultdict])
converter (BaseConverter)
default_factory (Callable[[], Any] | NothingType)
- Return type:
StructureHook
- cattrs.cols.homogenous_tuple_structure_factory(type, converter)[source]¶
A hook factory for homogenous (all elements the same, indeterminate length) tuples.
Converts any given iterable into a tuple.
- Parameters:
type (type)
converter (BaseConverter)
- Return type:
StructureHook
- cattrs.cols.is_abstract_set(type)[source]¶
A predicate function for abstract (collection.abc) sets.
- Return type:
bool
- cattrs.cols.is_any_set(type)[source]¶
A predicate function for both mutable and frozensets.
- Return type:
bool
- cattrs.cols.is_defaultdict(type)[source]¶
Is this type a defaultdict?
Bare defaultdicts (defaultdicts with no type arguments) are not supported since there’s no way to discover their _default_factory_.
- Parameters:
type (Any)
- Return type:
bool
- cattrs.cols.is_frozenset(type)[source]¶
A predicate function for frozensets.
Matches built-in frozensets and frozensets from the typing module.
- Parameters:
type (Any)
- Return type:
bool
- cattrs.cols.is_mapping(type)[source]¶
A predicate function for mappings.
- Parameters:
type (Any)
- Return type:
bool
- cattrs.cols.is_mutable_sequence(type)[source]¶
A predicate function for mutable sequences.
Matches lists, mutable sequences, and deques.
- Parameters:
type (Any)
- Return type:
bool
- cattrs.cols.is_namedtuple(type)[source]¶
A predicate function for named tuples.
- Parameters:
type (Any)
- Return type:
bool
- cattrs.cols.is_sequence(type)[source]¶
A predicate function for sequences.
Matches lists, sequences, mutable sequences, deques and homogenous tuples.
- Parameters:
type (Any)
- Return type:
bool
- cattrs.cols.is_set(type)¶
A predicate function for (mutable) sets.
Matches built-in sets and sets from the typing module.
- Parameters:
type (Any)
- Return type:
bool
- cattrs.cols.iterable_unstructure_factory(cl, converter, unstructure_to=None)[source]¶
A hook factory for unstructuring iterables.
- Parameters:
unstructure_to (Any) – Force unstructuring to this type, if provided.
cl (Any)
converter (BaseConverter)
- Return type:
UnstructureHook
Changed in version 24.2.0: typing.NoDefault is now correctly handled as Any.
- cattrs.cols.list_structure_factory(type, converter)[source]¶
A hook factory for structuring lists.
Converts any given iterable into a list.
- Parameters:
type (type)
converter (BaseConverter)
- Return type:
StructureHook
- cattrs.cols.mapping_structure_factory(cl, converter, structure_to=<class 'dict'>, key_type=NOTHING, val_type=NOTHING, detailed_validation='from_converter')[source]¶
Generate a specialized structure function for a mapping.
- Parameters:
cl (type[T])
converter (BaseConverter)
structure_to (type)
detailed_validation (bool | Literal['from_converter'])
- Return type:
SimpleStructureHook[Mapping[Any, Any], T]
- cattrs.cols.mapping_unstructure_factory(cl, converter, unstructure_to=None, key_handler=None)[source]¶
Generate a specialized unstructure function for a mapping.
- Parameters:
unstructure_to (Any) – The class to unstructure to; defaults to the same class as the mapping being unstructured.
cl (Any)
converter (BaseConverter)
key_handler (Callable[[Any, Any | None], Any] | None)
- Return type:
MappingUnstructureFn
- cattrs.cols.namedtuple_dict_structure_factory(cl, converter, detailed_validation='from_converter', forbid_extra_keys=False, use_linecache=True, /, **kwargs)[source]¶
A hook factory for hooks structuring namedtuples from dictionaries.
- Parameters:
forbid_extra_keys (bool) – Whether the hook should raise a ForbiddenExtraKeysError if unknown keys are encountered.
use_linecache (bool) – Whether to store the source code in the Python linecache.
cl (type[tuple])
converter (BaseConverter)
detailed_validation (bool | Literal['from_converter'])
kwargs (AttributeOverride)
- Return type:
StructureHook
Added in version 24.1.0.
- cattrs.cols.namedtuple_dict_unstructure_factory(cl, converter, omit_if_default=False, use_linecache=True, /, **kwargs)[source]¶
A hook factory for hooks unstructuring namedtuples to dictionaries.
- Parameters:
omit_if_default (bool) – When true, attributes equal to their default values will be omitted in the result dictionary.
use_linecache (bool) – Whether to store the source code in the Python linecache.
cl (type[tuple])
converter (BaseConverter)
kwargs (AttributeOverride)
- Return type:
UnstructureHook
Added in version 24.1.0.
- cattrs.cols.namedtuple_structure_factory(cl, converter)[source]¶
A hook factory for structuring namedtuples from iterables.
- Parameters:
cl (type[tuple])
converter (BaseConverter)
- Return type:
StructureHook
- cattrs.cols.namedtuple_unstructure_factory(cl, converter, unstructure_to=None)[source]¶
A hook factory for unstructuring namedtuples.
- Parameters:
unstructure_to (Any) – Force unstructuring to this type, if provided.
cl (type[tuple])
converter (BaseConverter)
- Return type:
UnstructureHook
cattrs.disambiguators module¶
Utilities for union (sum type) disambiguation.
- cattrs.disambiguators.create_default_dis_func(converter, *classes, use_literals=True, overrides='from_converter')[source]¶
Given attrs classes or dataclasses, generate a disambiguation function.
The function is based on unique fields without defaults or unique values.
- Parameters:
use_literals (bool) – Whether to try using fields annotated as literals for disambiguation.
overrides (dict[str, AttributeOverride] | Literal['from_converter']) – Attribute overrides to apply.
converter (BaseConverter)
classes (type[AttrsInstance])
- Return type:
Callable[[Mapping[Any, Any]], type[Any] | None]
Changed in version 24.1.0: Dataclasses are now supported.
cattrs.dispatch module¶
- class cattrs.dispatch.FunctionDispatch(converter, handler_pairs=NOTHING)[source]¶
Bases:
objectFunctionDispatch is similar to functools.singledispatch, but instead dispatches based on functions that take the type of the first argument in the method, and return True or False.
objects that help determine dispatch should be instantiated objects.
- Parameters:
converter (BaseConverter) – A converter to be used for factories that require converters.
handler_pairs (list[tuple[Predicate, Callable[[Any, Any], Any], bool, bool]])
Changed in version 24.1.0: Support for factories that require converters, hence this requires a converter when creating.
Method generated by attrs for class FunctionDispatch.
- register(predicate, func, is_generator=False, takes_converter=False)[source]¶
- Parameters:
predicate (Callable[[Any], bool])
func (Callable[[...], Any])
- Return type:
None
- dispatch(typ)[source]¶
Return the appropriate handler for the object passed.
- Parameters:
typ (Any)
- Return type:
Callable[[…], Any] | None
- copy_to(other, skip=0)[source]¶
- Parameters:
other (FunctionDispatch)
skip (int)
- Return type:
None
- class cattrs.dispatch.MultiStrategyDispatch(fallback_factory, converter)[source]¶
Bases:
Generic[Hook]MultiStrategyDispatch uses a combination of exact-match dispatch, singledispatch, and FunctionDispatch.
- Parameters:
fallback_factory (HookFactory[Hook]) – A hook factory to be called when a hook cannot be produced.
converter (BaseConverter) – A converter to be used for factories that require converters.
Changed in version 23.2.0: Fallbacks are now factories.
Changed in version 24.1.0: Support for factories that require converters, hence this requires a converter when creating.
- dispatch: Callable[[TargetType, BaseConverter], Hook]¶
- dispatch_without_caching(typ)[source]¶
Dispatch on the type but without caching the result.
- Parameters:
typ (Any)
- Return type:
Hook
- register_cls_list(cls_and_handler, direct=False)[source]¶
Register a class to direct or singledispatch.
- Parameters:
direct (bool)
- Return type:
None
- register_func_list(pred_and_handler)[source]¶
Register a predicate function to determine if the handler should be used for the type.
- Parameters:
pred_and_handler (list[tuple[Predicate, Any] | tuple[Predicate, Any, bool] | tuple[Predicate, Callable[[Any, BaseConverter], Any], Literal['extended']]]) – The list of predicates and their associated handlers. If a handler is registered in extended mode, it’s a factory that requires a converter.
- copy_to(other, skip=0)[source]¶
- Parameters:
other (MultiStrategyDispatch)
skip (int)
- Return type:
None
cattrs.errors module¶
- exception cattrs.errors.StructureHandlerNotFoundError(message, type_)[source]¶
Bases:
CattrsErrorError raised when structuring cannot find a handler for converting inputs into
type_.- Parameters:
message (str)
type_ (type)
- Return type:
None
- exception cattrs.errors.BaseValidationError(message, excs, cl)[source]¶
Bases:
ExceptionGroup,CattrsError- Parameters:
message (str)
excs (Sequence[Exception])
cl (type)
- Return type:
Self
- cl: type¶
- class cattrs.errors.IterableValidationNote(string, index, type)[source]¶
Bases:
strAttached as a note to an exception when an iterable element fails structuring.
- Parameters:
string (str)
index (int | str)
type (Any)
- Return type:
Self
- type: Any¶
- exception cattrs.errors.IterableValidationError(message, excs, cl)[source]¶
Bases:
BaseValidationErrorRaised when structuring an iterable.
- Parameters:
message (str)
excs (Sequence[Exception])
cl (type)
- Return type:
Self
- group_exceptions()[source]¶
Split the exceptions into two groups: with and without validation notes.
- Return type:
tuple[list[tuple[Exception, IterableValidationNote]], list[Exception]]
- class cattrs.errors.AttributeValidationNote(string, name, type)[source]¶
Bases:
strAttached as a note to an exception when an attribute fails structuring.
- Parameters:
string (str)
name (str)
type (Any)
- Return type:
Self
- name: str¶
- type: Any¶
- exception cattrs.errors.ClassValidationError(message, excs, cl)[source]¶
Bases:
BaseValidationErrorRaised when validating a class if any attributes are invalid.
- Parameters:
message (str)
excs (Sequence[Exception])
cl (type)
- Return type:
Self
- group_exceptions()[source]¶
Split the exceptions into two groups: with and without validation notes.
- Return type:
tuple[list[tuple[Exception, AttributeValidationNote]], list[Exception]]
- exception cattrs.errors.ForbiddenExtraKeysError(message, cl, extra_fields)[source]¶
Bases:
CattrsErrorRaised when forbid_extra_keys is activated and such extra keys are detected during structuring.
The attribute extra_fields is a sequence of those extra keys, which were the cause of this error, and cl is the class which was structured with those extra keys.
- Parameters:
message (str | None)
cl (type)
extra_fields (set[str])
- Return type:
None
cattrs.fns module¶
Useful internal functions.
- cattrs.fns.Predicate¶
A predicate function determines if a type can be handled.
alias of
Callable[[Any],bool]
cattrs.v module¶
Cattrs validation.
- cattrs.v.format_exception(exc, type)[source]¶
The default exception formatter, handling the most common exceptions.
The following exceptions are handled specially:
KeyErrors (required field missing)
ValueErrors (invalid value for type, expected <type> or just invalid value)
TypeErrors (invalid value for type, expected <type> and a couple special cases for iterables)
cattrs.ForbiddenExtraKeysError
some AttributeErrors (special cased for structing mappings)
- Parameters:
exc (BaseException)
type (type | None)
- Return type:
str
- cattrs.v.transform_error(exc, path='$', format_exception=<function format_exception>)[source]¶
Transform an exception into a list of error messages.
To get detailed error messages, the exception should be produced by a converter with detailed_validation set.
By default, the error messages are in the form of {description} @ {path}.
While traversing the exception and subexceptions, the path is formed:
by appending .{field_name} for fields in classes
by appending [{int}] for indices in iterables, like lists
by appending [{str}] for keys in mappings, like dictionaries
- Parameters:
exc (ClassValidationError | IterableValidationError | BaseException) – The exception to transform into error messages.
path (str) – The root path to use.
format_exception (Callable[[BaseException, type | None], str]) – A callable to use to transform Exceptions into string descriptions of errors.
- Return type:
list[str]
Added in version 23.1.0.