cattrs package#
Subpackages#
- cattrs.gen package
- cattrs.preconf package
- cattrs.strategies package
Submodules#
cattrs.converters module#
- class cattrs.converters.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 (Callable[[Any], Callable[[Any], Any]]) – A hook factory to be called when no registered unstructuring hooks match.
structure_fallback_factory (Callable[[Any], Callable[[Any, Any], Any]]) – 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
- 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:
- detailed_validation#
- register_structure_hook(cl, func)[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).
- Parameters:
cl (Any) –
func (Callable[[Any, Any], Any]) –
- Return type:
None
- register_structure_hook_factory(predicate, factory)[source]#
Register a hook factory for a given predicate.
- Parameters:
predicate (Callable[[Any], bool]) – A function that, given a type, returns whether the factory can produce a hook for that type.
factory (Callable[[Any], Callable[[Any, Any], Any]]) – A callable that, given a type, produces a structuring hook for that type. This structuring hook will be cached.
- Return type:
None
- 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[[Type[T]], bool]) –
func (Callable[[Any, Any], Any]) –
- Return type:
None
- register_unstructure_hook(cls, func)[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.
- Parameters:
cls (Any) –
func (Callable[[Any], Any]) –
- Return type:
None
- register_unstructure_hook_factory(predicate, factory)[source]#
Register a hook factory for a given predicate.
- Parameters:
predicate (Callable[[Any], bool]) – A function that, given a type, returns whether the factory can produce a hook for that type.
factory (Callable[[Any], Callable[[Any], Any]]) – A callable that, given a type, produces an unstructuring hook for that type. This unstructuring hook will be cached.
- Return type:
None
- 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
attrs
classes.
- unstructure(obj, unstructure_as=None)[source]#
- Parameters:
obj (Any) –
unstructure_as (Any) –
- Return type:
Any
- class cattrs.converters.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 (Callable[[Any], Callable[[Any], Any]]) – A hook factory to be called when no registered unstructuring hooks match.
structure_fallback_factory (Callable[[Any], Callable[[Any, Any], Any]]) – 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
- 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:
- forbid_extra_keys#
- 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 (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]
- gen_structure_typeddict(cl)[source]#
Generate a TypedDict structure 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_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]
- omit_if_default#
- type_overrides#
cattrs.disambiguators module#
Utilities for union (sum type) disambiguation.
- cattrs.disambiguators.create_default_dis_func(*classes, use_literals=True)[source]#
Given attrs classes, generate a disambiguation function.
The function is based on unique fields or unique values.
- Parameters:
use_literals (bool) – Whether to try using fields annotated as literals for disambiguation.
classes (Type[Any]) –
- Return type:
Callable[[Mapping[Any, Any]], Type[Any] | None]
cattrs.dispatch module#
- class cattrs.dispatch.FunctionDispatch(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.
Method generated by attrs for class FunctionDispatch.
- Parameters:
handler_pairs (List[Tuple[Callable[[Any], bool], Callable[[Any, Any], Any], bool]]) –
- copy_to(other, skip=0)[source]#
- Parameters:
other (FunctionDispatch) –
skip (int) –
- Return type:
None
- class cattrs.dispatch.MultiStrategyDispatch(fallback_factory)[source]#
Bases:
Generic
[Hook
]MultiStrategyDispatch uses a combination of exact-match dispatch, singledispatch, and FunctionDispatch.
- Parameters:
fallback_factory (Callable[[Any], Hook]) – A hook factory to be called when a hook cannot be produced.
Changed in version 23.2.0: Fallbacks are now factories.
Method generated by attrs for class MultiStrategyDispatch.
- copy_to(other, skip=0)[source]#
- Parameters:
other (MultiStrategyDispatch) –
skip (int) –
- Return type:
None
- dispatch: Callable[[Any], Hook]#
cattrs.errors module#
- 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.BaseValidationError(message, excs, cl)[source]#
Bases:
ExceptionGroup
- Parameters:
cl (Type) –
- cl: Type#
- 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
- 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]]
cattrs.fns module#
Useful internal functions.
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.
Module contents#
- 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#
- 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 (Callable[[Any], Callable[[Any], Any]]) – A hook factory to be called when no registered unstructuring hooks match.
structure_fallback_factory (Callable[[Any], Callable[[Any, Any], Any]]) – 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
- 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:
- detailed_validation#
- register_structure_hook(cl, func)[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).
- Parameters:
cl (Any) –
func (Callable[[Any, Any], Any]) –
- Return type:
None
- register_structure_hook_factory(predicate, factory)[source]#
Register a hook factory for a given predicate.
- Parameters:
predicate (Callable[[Any], bool]) – A function that, given a type, returns whether the factory can produce a hook for that type.
factory (Callable[[Any], Callable[[Any, Any], Any]]) – A callable that, given a type, produces a structuring hook for that type. This structuring hook will be cached.
- Return type:
None
- 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[[Type[T]], bool]) –
func (Callable[[Any, Any], Any]) –
- Return type:
None
- register_unstructure_hook(cls, func)[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.
- Parameters:
cls (Any) –
func (Callable[[Any], Any]) –
- Return type:
None
- register_unstructure_hook_factory(predicate, factory)[source]#
Register a hook factory for a given predicate.
- Parameters:
predicate (Callable[[Any], bool]) – A function that, given a type, returns whether the factory can produce a hook for that type.
factory (Callable[[Any], Callable[[Any], Any]]) – A callable that, given a type, produces an unstructuring hook for that type. This unstructuring hook will be cached.
- Return type:
None
- 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
attrs
classes.
- unstructure(obj, unstructure_as=None)[source]#
- Parameters:
obj (Any) –
unstructure_as (Any) –
- Return 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]]
- 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 (Callable[[Any], Callable[[Any], Any]]) – A hook factory to be called when no registered unstructuring hooks match.
structure_fallback_factory (Callable[[Any], Callable[[Any, Any], Any]]) – 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
- 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:
- forbid_extra_keys#
- 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 (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]
- gen_structure_typeddict(cl)[source]#
Generate a TypedDict structure 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_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]
- omit_if_default#
- type_overrides#
- 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#
- 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
- 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'#
- 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)#
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).
- Parameters:
cl (Any) –
func (Callable[[Any, Any], Any]) –
- 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[[Type[T]], bool]) –
func (Callable[[Any, Any], Any]) –
- Return type:
None
- cattrs.register_unstructure_hook(cls, func)#
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.
- Parameters:
cls (Any) –
func (Callable[[Any], Any]) –
- 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.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]
New in version 23.1.0.
- cattrs.unstructure(obj, unstructure_as=None)#
- Parameters:
obj (Any) –
unstructure_as (Any) –
- Return type:
Any