cattr package#

Subpackages#

Submodules#

cattr.converters module#

class cattr.converters.BaseConverter(dict_factory=<class 'dict'>, unstruct_strat=UnstructureStrategy.AS_DICT, prefer_attrib_converters=False, detailed_validation=True)[source]#

Bases: object

Converts between structured and unstructured data.

Parameters
  • dict_factory (Callable[[], Any]) –

  • unstruct_strat (UnstructureStrategy) –

  • prefer_attrib_converters (bool) –

  • detailed_validation (bool) –

copy(dict_factory=None, unstruct_strat=None, prefer_attrib_converters=None, detailed_validation=None)[source]#
Parameters
  • dict_factory (Optional[Callable[[], Any]]) –

  • unstruct_strat (Optional[UnstructureStrategy]) –

  • prefer_attrib_converters (Optional[bool]) –

  • detailed_validation (Optional[bool]) –

Return type

BaseConverter

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, Type[T]], T]) –

Return type

None

register_structure_hook_factory(predicate, factory)[source]#

Register a hook factory for a given predicate.

A predicate is a function that, given a type, returns whether the factory can produce a hook for that type.

A factory is a callable that, given a type, produces a structuring hook for that type. This structuring hook will be cached.

Parameters
  • predicate (Callable[[Any], bool]) –

  • factory (Callable[[Any], Callable[[Any, Any], Any]]) –

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, Type[T]], T]) –

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.

A predicate is a function that, given a type, returns whether the factory can produce a hook for that type.

A factory is a callable that, given a type, produces an unstructuring hook for that type. This unstructuring hook will be cached.

Parameters
  • predicate (Callable[[Any], bool]) –

  • factory (Callable[[Any], Callable[[Any], Any]]) –

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 (Optional[Any]) –

Return type

Any

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, …]

class cattr.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)[source]#

Bases: BaseConverter

A converter which generates specialized un/structuring functions.

Parameters
  • 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) –

  • detailed_validation (bool) –

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]#
Parameters
  • dict_factory (Optional[Callable[[], Any]]) –

  • unstruct_strat (Optional[UnstructureStrategy]) –

  • omit_if_default (Optional[bool]) –

  • forbid_extra_keys (Optional[bool]) –

  • type_overrides (Optional[Mapping[Type, AttributeOverride]]) –

  • unstruct_collection_overrides (Optional[Mapping[Type, Callable]]) –

  • prefer_attrib_converters (Optional[bool]) –

  • detailed_validation (Optional[bool]) –

Return type

Converter

forbid_extra_keys#
gen_structure_annotated(type)[source]#
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_annotated(type)[source]#
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 (Optional[Any]) –

Return type

Callable[[Tuple[Any, …]], Any]

gen_unstructure_iterable(cl, unstructure_to=None)[source]#
Parameters
  • cl (Any) –

  • unstructure_to (Optional[Any]) –

Return type

Callable[[Iterable[Any]], Any]

gen_unstructure_mapping(cl, unstructure_to=None, key_handler=None)[source]#
Parameters
  • cl (Any) –

  • unstructure_to (Optional[Any]) –

  • key_handler (Optional[Callable[[Any, Optional[Any]], Any]]) –

Return type

Callable[[Mapping[Any, Any]], 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#
cattr.converters.GenConverter#

alias of Converter

class cattr.converters.UnstructureStrategy(value)[source]#

Bases: Enum

attrs classes unstructuring strategies.

AS_DICT = 'asdict'#
AS_TUPLE = 'astuple'#

cattr.disambiguators module#

cattr.disambiguators.create_uniq_field_dis_func(*classes)[source]#

Given attr classes, generate a disambiguation function.

The function is based on unique fields.

Parameters

classes (Type[Any]) –

Return type

Callable[[Mapping[Any, Any]], Optional[Type[Any]]]

cattr.dispatch module#

class cattr.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.

Parameters

handler_pairs (List[Tuple[Callable[[Any], bool], Callable[[Any, Any], Any], bool]]) –

copy_to(other, skip=0)[source]#
Parameters
dispatch(typ)[source]#

returns the appropriate handler, for the object passed.

Parameters

typ (Any) –

Return type

Optional[Callable[[Any, Any], Any]]

get_num_fns()[source]#
Return type

int

register(can_handle, func, is_generator=False)[source]#
Parameters

can_handle (Callable[[Any], bool]) –

class cattr.dispatch.MultiStrategyDispatch(fallback_func)[source]#

Bases: object

MultiStrategyDispatch uses a combination of exact-match dispatch, singledispatch, and FunctionDispatch.

Parameters

fallback_func (Callable[[Any, Any], Any]) –

clear_cache()[source]#

Clear all caches.

clear_direct()[source]#

Clear the direct dispatch.

copy_to(other, skip=0)[source]#
Parameters
dispatch#
get_num_fns()[source]#
Return type

int

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 handle should be used for the type.

Parameters

pred_and_handler (List[Union[Tuple[Callable[[Any], bool], Any], Tuple[Callable[[Any], bool], Any, bool]]]) –

cattr.errors module#

exception cattr.errors.BaseValidationError(message, excs, cl)[source]#

Bases: ExceptionGroup

Parameters

cl (Type) –

cl: Type#
derive(excs)[source]#
exception cattr.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 cattr.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 (Optional[str]) –

  • cl (Type) –

  • extra_fields (Set[str]) –

Return type

None

exception cattr.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]]

exception cattr.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

cattr.gen module#

class cattr.gen.AttributeOverride(omit_if_default=None, rename=None, omit=False, struct_hook=None, unstruct_hook=None)[source]#

Bases: object

Parameters
  • omit_if_default (Optional[bool]) –

  • rename (Optional[str]) –

  • omit (bool) –

  • struct_hook (Optional[Callable[[Any, Any], Any]]) –

  • unstruct_hook (Optional[Callable[[Any], Any]]) –

omit: bool#
omit_if_default: Optional[bool]#
rename: Optional[str]#
struct_hook: Optional[Callable[[Any, Any], Any]]#
unstruct_hook: Optional[Callable[[Any], Any]]#
cattr.gen.make_dict_structure_fn(cl, converter, _cattrs_forbid_extra_keys=False, _cattrs_use_linecache=True, _cattrs_prefer_attrib_converters=False, _cattrs_detailed_validation=True, **kwargs)[source]#

Generate a specialized dict structuring function for an attrs class.

Parameters
  • cl (Type[T]) –

  • converter (BaseConverter) –

  • _cattrs_forbid_extra_keys (bool) –

  • _cattrs_use_linecache (bool) –

  • _cattrs_prefer_attrib_converters (bool) –

  • _cattrs_detailed_validation (bool) –

  • kwargs (AttributeOverride) –

Return type

DictStructureFn[T]

cattr.gen.make_dict_unstructure_fn(cl, converter, _cattrs_omit_if_default=False, _cattrs_use_linecache=True, **kwargs)[source]#

Generate a specialized dict unstructuring function for an attrs class or a dataclass.

Parameters
Return type

Callable[[T], Dict[str, Any]]

cattr.gen.make_hetero_tuple_unstructure_fn(cl, converter, unstructure_to=None)[source]#

Generate a specialized unstructure function for a heterogenous tuple.

Parameters
  • cl (Any) –

  • converter (BaseConverter) –

  • unstructure_to (Any) –

Return type

HeteroTupleUnstructureFn

cattr.gen.make_iterable_unstructure_fn(cl, converter, unstructure_to=None)[source]#

Generate a specialized unstructure function for an iterable.

Parameters
  • cl (Any) –

  • converter (BaseConverter) –

  • unstructure_to (Any) –

Return type

IterableUnstructureFn

cattr.gen.make_mapping_structure_fn(cl, converter, structure_to=<class 'dict'>, key_type=_Nothing.NOTHING, val_type=_Nothing.NOTHING, detailed_validation=True)[source]#

Generate a specialized unstructure function for a mapping.

Parameters
  • cl (Type[T]) –

  • converter (BaseConverter) –

  • structure_to (Type) –

  • detailed_validation (bool) –

Return type

MappingStructureFn[T]

cattr.gen.make_mapping_unstructure_fn(cl, converter, unstructure_to=None, key_handler=None)[source]#

Generate a specialized unstructure function for a mapping.

Parameters
  • cl (Any) –

  • converter (BaseConverter) –

  • unstructure_to (Any) –

  • key_handler (Optional[Callable[[Any, Optional[Any]], Any]]) –

Return type

MappingUnstructureFn

cattr.gen.override(omit_if_default=None, rename=None, omit=False, struct_hook=None, unstruct_hook=None)[source]#
Parameters
  • omit_if_default (Optional[bool]) –

  • rename (Optional[str]) –

  • omit (bool) –

  • struct_hook (Optional[Callable[[Any, Any], Any]]) –

  • unstruct_hook (Optional[Callable[[Any], Any]]) –

Module contents#

class cattr.BaseConverter(dict_factory=<class 'dict'>, unstruct_strat=UnstructureStrategy.AS_DICT, prefer_attrib_converters=False, detailed_validation=True)[source]#

Bases: object

Converts between structured and unstructured data.

Parameters
  • dict_factory (Callable[[], Any]) –

  • unstruct_strat (UnstructureStrategy) –

  • prefer_attrib_converters (bool) –

  • detailed_validation (bool) –

copy(dict_factory=None, unstruct_strat=None, prefer_attrib_converters=None, detailed_validation=None)[source]#
Parameters
  • dict_factory (Optional[Callable[[], Any]]) –

  • unstruct_strat (Optional[UnstructureStrategy]) –

  • prefer_attrib_converters (Optional[bool]) –

  • detailed_validation (Optional[bool]) –

Return type

BaseConverter

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, Type[T]], T]) –

Return type

None

register_structure_hook_factory(predicate, factory)[source]#

Register a hook factory for a given predicate.

A predicate is a function that, given a type, returns whether the factory can produce a hook for that type.

A factory is a callable that, given a type, produces a structuring hook for that type. This structuring hook will be cached.

Parameters
  • predicate (Callable[[Any], bool]) –

  • factory (Callable[[Any], Callable[[Any, Any], Any]]) –

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, Type[T]], T]) –

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.

A predicate is a function that, given a type, returns whether the factory can produce a hook for that type.

A factory is a callable that, given a type, produces an unstructuring hook for that type. This unstructuring hook will be cached.

Parameters
  • predicate (Callable[[Any], bool]) –

  • factory (Callable[[Any], Callable[[Any], Any]]) –

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 (Optional[Any]) –

Return type

Any

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, …]

class cattr.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)[source]#

Bases: BaseConverter

A converter which generates specialized un/structuring functions.

Parameters
  • 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) –

  • detailed_validation (bool) –

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]#
Parameters
  • dict_factory (Optional[Callable[[], Any]]) –

  • unstruct_strat (Optional[UnstructureStrategy]) –

  • omit_if_default (Optional[bool]) –

  • forbid_extra_keys (Optional[bool]) –

  • type_overrides (Optional[Mapping[Type, AttributeOverride]]) –

  • unstruct_collection_overrides (Optional[Mapping[Type, Callable]]) –

  • prefer_attrib_converters (Optional[bool]) –

  • detailed_validation (Optional[bool]) –

Return type

Converter

forbid_extra_keys#
gen_structure_annotated(type)[source]#
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_annotated(type)[source]#
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 (Optional[Any]) –

Return type

Callable[[Tuple[Any, …]], Any]

gen_unstructure_iterable(cl, unstructure_to=None)[source]#
Parameters
  • cl (Any) –

  • unstructure_to (Optional[Any]) –

Return type

Callable[[Iterable[Any]], Any]

gen_unstructure_mapping(cl, unstructure_to=None, key_handler=None)[source]#
Parameters
  • cl (Any) –

  • unstructure_to (Optional[Any]) –

  • key_handler (Optional[Callable[[Any, Optional[Any]], Any]]) –

Return type

Callable[[Mapping[Any, Any]], 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#
cattr.GenConverter#

alias of Converter

class cattr.UnstructureStrategy(value)[source]#

Bases: Enum

attrs classes unstructuring strategies.

AS_DICT = 'asdict'#
AS_TUPLE = 'astuple'#
cattr.override(omit_if_default=None, rename=None, omit=False, struct_hook=None, unstruct_hook=None)[source]#
Parameters
  • omit_if_default (Optional[bool]) –

  • rename (Optional[str]) –

  • omit (bool) –

  • struct_hook (Optional[Callable[[Any, Any], Any]]) –

  • unstruct_hook (Optional[Callable[[Any], Any]]) –

cattr.structure(obj, cl)#

Convert unstructured Python data structures to structured data.

Parameters
  • obj (Any) –

  • cl (Type[T]) –

Return type

T

cattr.structure_attrs_fromdict(obj, cl)#

Instantiate an attrs class from a mapping (dict).

Parameters
  • obj (Mapping[str, Any]) –

  • cl (Type[T]) –

Return type

T

cattr.structure_attrs_fromtuple(obj, cl)#

Load an attrs class from a sequence (tuple).

Parameters
  • obj (Tuple[Any, ...]) –

  • cl (Type[T]) –

Return type

T

cattr.unstructure(obj, unstructure_as=None)#
Parameters
  • obj (Any) –

  • unstructure_as (Optional[Any]) –

Return type

Any