cattrs package#
- cattrs.structure(obj, cl)#
Convert unstructured Python data structures to structured data.
- Parameters:
obj (Any) –
cl (type[~T]) –
- Return type:
T
- cattrs.unstructure(obj, unstructure_as=None)#
- Parameters:
obj (Any) –
unstructure_as (Any) –
- Return type:
Any
- 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]
New 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]
New in version 24.1.0.
- 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_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.
- Parameters:
cl (Any) –
func (Callable[[Any, Any], Any] | None) –
- Return type:
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.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.
- Parameters:
cls (Any) –
func (UnstructureHook | None) –
- Return type:
Callable[[UnstructureHook]] | None
- 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.global_converter: Final = <cattrs.converters.Converter object>#
The global converter. Prefer creating your own if customizations are required.
- 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:
object
Converts 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) –
New in version 23.2.0: unstructure_fallback_factory
New 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#
- unstructure(obj, unstructure_as=None)[source]#
- Parameters:
obj (Any) –
unstructure_as (Any) –
- Return type:
Any
- property unstruct_strat: UnstructureStrategy#
The default way of unstructuring
attrs
classes.
- register_unstructure_hook(cls: UnstructureHookT) UnstructureHookT [source]#
- register_unstructure_hook(cls: Any, func: Callable[[Any], Any]) 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.
- 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
- register_unstructure_hook_factory(predicate: Callable[[Any], bool]) Callable[[AnyUnstructureHookFactoryBase], AnyUnstructureHookFactoryBase] [source]#
- register_unstructure_hook_factory(predicate: Callable[[Any], bool], factory: UnstructureHookFactory) UnstructureHookFactory
- register_unstructure_hook_factory(predicate: Callable[[Any], bool], factory: Callable[[Any, BaseConverter], Callable[[Any], Any]]) Callable[[Any, BaseConverter], Callable[[Any], Any]]
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.
- 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]
New in version 24.1.0.
- register_structure_hook(cl: StructureHookT) StructureHookT [source]#
- register_structure_hook(cl: Any, func: Callable[[Any, Any], Any]) 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.
- 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_structure_hook_factory(predicate: Callable[[Any], bool]) Callable[[AnyStructureHookFactoryBase], AnyStructureHookFactoryBase] [source]#
- register_structure_hook_factory(predicate: Callable[[Any], bool], factory: StructureHookFactory) StructureHookFactory
- register_structure_hook_factory(predicate: Callable[[Any], bool], factory: Callable[[Any, BaseConverter], Callable[[Any, Any], Any]]) Callable[[Any, BaseConverter], Callable[[Any, Any], Any]]
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.
- structure(obj, cl)[source]#
Convert unstructured Python data structures to structured data.
- Parameters:
obj (Any) –
cl (type[~T]) –
- Return type:
T
- 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]
New in version 24.1.0.
- unstructure_attrs_asdict(obj)[source]#
Our version of attrs.asdict, so we can call back to us.
- Parameters:
obj (Any) –
- Return type:
dict[str, Any]
- unstructure_attrs_astuple(obj)[source]#
Our version of attrs.astuple, so we can call back to us.
- Parameters:
obj (Any) –
- Return type:
tuple[Any, …]
- structure_attrs_fromtuple(obj, cl)[source]#
Load an attrs class from a sequence (tuple).
- Parameters:
obj (tuple[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
- 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:
- 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>>)[source]#
Bases:
BaseConverter
A 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.
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, Callable]) –
prefer_attrib_converters (bool) –
New in version 23.2.0: unstructure_fallback_factory
New 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.
- omit_if_default#
- forbid_extra_keys#
- type_overrides#
- register_unstructure_hook_factory(predicate: Callable[[Any], bool]) Callable[[AnyUnstructureHookFactory], AnyUnstructureHookFactory] [source]#
- register_unstructure_hook_factory(predicate: Callable[[Any], bool], factory: UnstructureHookFactory) UnstructureHookFactory
- register_unstructure_hook_factory(predicate: Callable[[Any], bool], factory: Callable[[Any, Converter], Callable[[Any], Any]]) Callable[[Any, Converter], Callable[[Any], Any]]
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_structure_hook_factory(predicate: Callable[[Any], bool]) Callable[[AnyStructureHookFactory], AnyStructureHookFactory] [source]#
- register_structure_hook_factory(predicate: Callable[[Any], bool], factory: StructureHookFactory) StructureHookFactory
- register_structure_hook_factory(predicate: Callable[[Any], bool], factory: Callable[[Any, Converter], Callable[[Any, Any], Any]]) Callable[[Any, Converter], Callable[[Any, Any], Any]]
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.
- get_structure_newtype(type)[source]#
- Parameters:
type (type[~T]) –
- Return type:
Callable[[Any, Any], T]
- gen_unstructure_typeddict(cl)[source]#
Generate a TypedDict unstructure function.
Also apply converter-scored modifications.
- Parameters:
cl (Any) –
- Return type:
Callable[[dict], dict]
- gen_unstructure_attrs_fromdict(cl)[source]#
- Parameters:
cl (type[~T]) –
- Return type:
Callable[[T], dict[str, Any]]
- gen_unstructure_optional(cl)[source]#
Generate an unstructuring hook for optional types.
- Parameters:
cl (type[~T]) –
- Return type:
Callable[[T], 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_structure_attrs_fromdict(cl)[source]#
- Parameters:
cl (type[~T]) –
- Return type:
Callable[[Mapping[str, Any], Any], T]
- gen_unstructure_iterable(cl, unstructure_to=None)[source]#
- Parameters:
cl (Any) –
unstructure_to (Any) –
- Return type:
Callable[[Iterable[Any]], Any]
- gen_unstructure_hetero_tuple(cl, unstructure_to=None)[source]#
- Parameters:
cl (Any) –
unstructure_to (Any) –
- Return type:
Callable[[Tuple[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_structure_counter(cl)[source]#
- Parameters:
cl (Any) –
- Return type:
Callable[[Mapping[Any, Any], Any], T]
- gen_structure_mapping(cl)[source]#
- Parameters:
cl (Any) –
- Return type:
Callable[[Mapping[Any, Any], Any], T]
- 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)[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] | None) –
prefer_attrib_converters (bool | None) –
- Return type:
- class cattrs.AttributeValidationNote(string, name, type)[source]#
Bases:
str
Attached as a note to an exception when an attribute fails structuring.
- Parameters:
string (str) –
name (str) –
type (Any) –
- Return type:
- name: str#
- type: Any#
- exception cattrs.BaseValidationError(message, excs, cl)[source]#
Bases:
ExceptionGroup
- Parameters:
cl (Type) –
- cl: Type#
- exception cattrs.ClassValidationError(message, excs, cl)[source]#
Bases:
BaseValidationError
Raised when validating a class if any attributes are invalid.
- Parameters:
cl (Type) –
- 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.ForbiddenExtraKeysError(message, cl, extra_fields)[source]#
Bases:
Exception
Raised 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:
BaseValidationError
Raised when structuring an iterable.
- Parameters:
cl (Type) –
- 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:
str
Attached as a note to an exception when an iterable element fails structuring.
- Parameters:
string (str) –
index (int | str) –
type (Any) –
- Return type:
- type: Any#
- 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
- exception cattrs.StructureHandlerNotFoundError(message, type_)[source]#
Bases:
Exception
Error raised when structuring cannot find a handler for converting inputs into
type_
.- Parameters:
message (str) –
type_ (Type) –
- Return type:
None
- 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]
New in version 23.1.0.
- class cattrs.UnstructureStrategy(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
Bases:
Enum
attrs classes unstructuring strategies.
- AS_DICT = 'asdict'#
- AS_TUPLE = 'astuple'#
Subpackages#
- cattrs.gen package
- cattrs.preconf package
validate_datetime()
wrap()
- Submodules
- cattrs.preconf.bson module
- cattrs.preconf.cbor2 module
- cattrs.preconf.json module
- cattrs.preconf.msgpack module
- cattrs.preconf.msgspec module
- cattrs.preconf.orjson module
- cattrs.preconf.pyyaml module
- cattrs.preconf.tomlkit module
- cattrs.preconf.ujson module
- cattrs.strategies package
Submodules#
cattrs.cols module#
Utility functions for collections.
- cattrs.cols.is_any_set(type)[source]#
A predicate function for both mutable and frozensets.
- 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_namedtuple(type)[source]#
A predicate function for named tuples.
- 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_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.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.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.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.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
New 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
New in version 24.1.0.
- cattrs.cols.mapping_structure_factory(cl, converter, structure_to=<class 'dict'>, key_type=_Nothing.NOTHING, val_type=_Nothing.NOTHING, detailed_validation=True)[source]#
Generate a specialized structure function for a mapping.
- Parameters:
cl (type[T]) –
converter (BaseConverter) –
structure_to (type) –
detailed_validation (bool) –
- Return type:
MappingStructureFn[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.disambiguators module#
Utilities for union (sum type) disambiguation.
- cattrs.disambiguators.is_supported_union(typ)[source]#
Whether the type is a union of attrs classes.
- Parameters:
typ (Any) –
- Return type:
bool
- 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.NOTHING)[source]#
Bases:
object
FunctionDispatch 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:
Exception
Error 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
- Parameters:
cl (Type) –
- cl: Type#
- class cattrs.errors.IterableValidationNote(string, index, type)[source]#
Bases:
str
Attached as a note to an exception when an iterable element fails structuring.
- Parameters:
string (str) –
index (int | str) –
type (Any) –
- Return type:
- type: Any#
- exception cattrs.errors.IterableValidationError(message, excs, cl)[source]#
Bases:
BaseValidationError
Raised when structuring an iterable.
- Parameters:
cl (Type) –
- 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:
str
Attached as a note to an exception when an attribute fails structuring.
- Parameters:
string (str) –
name (str) –
type (Any) –
- Return type:
- name: str#
- type: Any#
- exception cattrs.errors.ClassValidationError(message, excs, cl)[source]#
Bases:
BaseValidationError
Raised when validating a class if any attributes are invalid.
- Parameters:
cl (Type) –
- 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:
Exception
Raised 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]
New in version 23.1.0.