Public API¶
Entry points¶
- class compages.Structurer(handlers: Mapping[Any, StructureHandler] = {})[source]¶
- structure_into(structure_into: type[_T] | TypedNewType[_T], val: Any, user_context: Any | None = None) _T[source]¶
Structures (deserializes) the given
valueinto the typestructure_intowith an optionaluser_context(which will be passed to the handlers).Raises
StructuringErrorfor any structuring-related error.
- class compages.Unstructurer(handlers: Mapping[Any, UnstructureHandler] = {})[source]¶
- unstructure_as(unstructure_as: type[_T] | TypedNewType[_T], val: _T, user_context: Any | None = None) Any[source]¶
Unstructures (serializes) the given
valueas the typeunstructure_aswith an optionaluser_context(which will be passed to the handlers).Calls
isinstance_ext()at the beginning, raisingUnstructuringErroron failure.Raises
UnstructuringErrorfor any unstructuring-related error.
Custom handlers¶
- class compages.StructureHandler[source]¶
A base class for structuring logic attached to a type.
- simple_structure(value: Any) Any[source]¶
Structures the given
value.Use for the cases where the information from
contextis not needed. Ifstructure()is not defined, this method must be defined.
- structure(context: StructurerContext, value: Any) Any[source]¶
Structures the given
valuereturning an instance ofcontext.structure_into.If not defined, falls back to
simple_structure().
- class compages.StructurerContext[source]¶
A context object passed to handlers during structuring.
- nested_structure_into(structure_into: type[_T] | TypedNewType[_T], val: Any) _T[source]¶
Calls
Structurer.structure_into()ofself.structurerpassing on the user context.
- structure_into: type[Any] | TypedNewType[Any]¶
The requested return value type.
Can be a regular type, a newtype, or a generic type.
- structurer: Structurer¶
The current structurer.
- user_context: Any¶
The custom object the user passed to
Unstructurer.unstructure_as().
- class compages.UnstructureHandler[source]¶
A base class for unstructuring logic attached to a type.
- simple_unstructure(value: Any) Any[source]¶
Unstructures the given
value.Use for the cases where the information from
contextis not needed. Ifunstructure()is not defined, this method must be defined.
- unstructure(context: UnstructurerContext, value: Any) Any[source]¶
Unstructures (serializes) the given
valuegivencontext.It is guaranteed that
isinstance_ext(val, get_lookup_order(context.unstructure_as)) == True(seeisinstance_ext()andget_lookup_order()).
- class compages.UnstructurerContext[source]¶
A context object passed to handlers during unstructuring.
- nested_unstructure_as(unstructure_as: type[_T] | TypedNewType[_T], val: _T) Any[source]¶
Calls
Unstructurer.unstructure_as()ofself.unstructurerpassing on the user context.
- unstructure_as: type[Any] | TypedNewType[Any]¶
The type which the value should be treated as.
Can be a regular type, a newtype, or a generic type.
- unstructurer: Unstructurer¶
The current unstructurer.
- user_context: Any¶
The custom object the user passed to
Unstructurer.unstructure_as().
- class compages.StructLikeOptions(to_unstructured_name: ~collections.abc.Callable[[str, ~typing.Any], str] = <function StructLikeOptions.<lambda>>, unstructure_skip_defaults: bool = True, structure_fill_in_defaults: bool = True)[source]¶
Options for handlers working with struct-like types (dataclasses, named tuples etc).
- to_unstructured_name(_metadata)¶
A function converting a field name of a typed representation into a field name of the corresponding unstructured representation.
The second argument is the metadata attached to the field (if any).
Type resolution¶
- class compages.DataclassBase[source]¶
A marker type for built-in dataclasses (since they don’t have a common base type). Use to attach dataclass-related handlers (e.g.
IntoDataclassFromMapping).
- class compages.NamedTupleBase[source]¶
A marker type for built-in named tuples (since they don’t have a common base type). Use to attach NamedTuple-related handlers (e.g.
IntoNamedTupleFromMapping).
Type resolution (hazmat)¶
These functions define the logic of type lookup in structurers and unstructurers. They are not supposed to be used by themselves, they are exported to keep the documentation of that logic in one place.
- class compages.TypedNewType[source]¶
Bases:
Protocol,Generic[_T_co]Unfortunately,
typing.NewTypein Python is not generic, so we cannot express the concept of “the type of instances of of this type, given the type’s type annotation”.This protocol covers any instance of
typing.NewTypeand has the same properties astype[_T].
- compages.get_lookup_order(tp: type[Any] | TypedNewType[Any]) list[type[Any] | TypedNewType[Any]][source]¶
Returns the structuring/unstructuring handler lookup order for regular types, generic types, or newtypes.
The order is the following:
For a regular type, it equals to its
.mro()without the last element (builtins.object).For a :py:class`typing.NewType` instance, the order is the
tpfollowed by the lookup order fortp.__supertype__.For a generic (something with a non-
Nonetyping.get_origin()), the order istpfollowed by the lookup order for the origin.For a dataclass, a
DataclassBasemarker type is appended to the end of the returned list.For a named tuple, a
NamedTupleBasemarker type is inserted just beforetuple.
Note
If you want to assign a handler for generic unions, note that
typing.Union[...]has the origintyping.Union, buttype1 | type2 | ...has the origintypes.UnionType.
- compages.isinstance_ext(val: Any, lookup_order: list[type[Any] | TypedNewType[Any]]) bool[source]¶
An extended
isinstance()working with newtypes and generic types.Instead of an actual type
tptakes the return value ofget_lookup_order(tp)(for performance reasons).If
tpis a regular type, returnsisinstance(val, tp).If
tpis a NewType, returnsisinstance(val, base_tp)wherebase_tpis the first regular supertype of the newtype hierarchy.If
tpis a generic,isinstance_ext()does not attempt to introspect the value (not that it has any means to, at this level), only checking forisinstance()with the origin. That is,isinstance_ext(val, list[int]) == isinstance(val, list), regardless of what type the elements of val are (checking that is the responsibility of handlers).All generics are currently assumed to be covariant.
As a corollary or that,
isinstance_ext(val, UnionType[...])is alwaysTrue.
Built-in structuring handlers¶
- class compages.IntoBool[source]¶
Bases:
StructureHandlerIf
valis abool, structures into itself, otherwise raises aStructuringError.
- class compages.IntoBytes[source]¶
Bases:
StructureHandlerIf
valis abytes, structures into itself, otherwise raises aStructuringError.
- class compages.IntoDataclassFromMapping(options: ~compages._struct_like.StructLikeOptions = StructLikeOptions(to_unstructured_name=<function StructLikeOptions.<lambda>>, unstructure_skip_defaults=True, structure_fill_in_defaults=True))[source]¶
Bases:
StructureHandlerAttempts to structure into a
dataclass()instance from aMappingtype.
- class compages.IntoDataclassFromSequence(options: ~compages._struct_like.StructLikeOptions = StructLikeOptions(to_unstructured_name=<function StructLikeOptions.<lambda>>, unstructure_skip_defaults=True, structure_fill_in_defaults=True))[source]¶
Bases:
StructureHandlerAttempts to structure into a
dataclass()instance from aSequencetype.
- class compages.IntoDict[source]¶
Bases:
StructureHandlerAttempts to structure into a
dictgiven its type arguments.If the requested type is an unqalified
dict, it is treated asdict[Any, Any].
- class compages.IntoFloat[source]¶
Bases:
StructureHandlerIf
valis afloatorint, converts intofloat, otherwise raises aStructuringError.
- class compages.IntoInt[source]¶
Bases:
StructureHandlerIf
valis anint(but notbool), structures into itself, otherwise raises aStructuringError.
- class compages.IntoList[source]¶
Bases:
StructureHandlerAttempts to structure into a
listgiven its type arguments.If the requested type is an unqalified
list, it is treated aslist[Any].
- class compages.IntoNamedTupleFromMapping(options: ~compages._struct_like.StructLikeOptions = StructLikeOptions(to_unstructured_name=<function StructLikeOptions.<lambda>>, unstructure_skip_defaults=True, structure_fill_in_defaults=True))[source]¶
Bases:
StructureHandlerAttempts to structure into a
NamedTupleinstance from aMappingtype.
- class compages.IntoNamedTupleFromSequence(options: ~compages._struct_like.StructLikeOptions = StructLikeOptions(to_unstructured_name=<function StructLikeOptions.<lambda>>, unstructure_skip_defaults=True, structure_fill_in_defaults=True))[source]¶
Bases:
StructureHandlerAttempts to structure into a
NamedTupleinstance from aSequencetype.
- class compages.IntoNone[source]¶
Bases:
StructureHandlerIf
valisNone, structures into itself, otherwise raises aStructuringError.
- class compages.IntoStr[source]¶
Bases:
StructureHandlerIf
valis astr, structures into itself, otherwise raises aStructuringError.
- class compages.IntoTuple[source]¶
Bases:
StructureHandlerAttempts to structure into a
tuplegiven its type arguments.If the requested type is an unqalified
tuple, it is treated astuple[Any, ...].
- class compages.IntoUnion[source]¶
Bases:
StructureHandlerAttempts to structure into every type in the union in order, returns the result of the first succeeded call.
If none succeeded, raises a
StructuringError.
Built-in structuring handlers¶
- class compages.AsBool[source]¶
Bases:
UnstructureHandlerUnstructures anything convertable to a
boolas abool.
- class compages.AsBytes[source]¶
Bases:
UnstructureHandlerUnstructures anything convertable to
bytesasbytes.
- class compages.AsDataclassToDict(options: ~compages._struct_like.StructLikeOptions = StructLikeOptions(to_unstructured_name=<function StructLikeOptions.<lambda>>, unstructure_skip_defaults=True, structure_fill_in_defaults=True))[source]¶
Bases:
UnstructureHandlerUnstructures a
dataclass()instance into adict.
- class compages.AsDataclassToList(options: ~compages._struct_like.StructLikeOptions = StructLikeOptions(to_unstructured_name=<function StructLikeOptions.<lambda>>, unstructure_skip_defaults=True, structure_fill_in_defaults=True))[source]¶
Bases:
UnstructureHandlerUnstructures a
dataclass()instance into alist.
- class compages.AsDict[source]¶
Bases:
UnstructureHandlerUnstructures as a
dictgiven its type arguments.If the requested type is an unqalified
dict, it is treated asdict[Any, Any].
- class compages.AsFloat[source]¶
Bases:
UnstructureHandlerUnstructures anything convertable to a
floatas afloat.
- class compages.AsInt[source]¶
Bases:
UnstructureHandlerUnstructures anything convertable to an
int(but notbool) as anint.
- class compages.AsList[source]¶
Bases:
UnstructureHandlerUnstructures as a
listgiven its type arguments.If the requested type is an unqalified
list, it is treated aslist[Any].
- class compages.AsNamedTupleToDict(options: ~compages._struct_like.StructLikeOptions = StructLikeOptions(to_unstructured_name=<function StructLikeOptions.<lambda>>, unstructure_skip_defaults=True, structure_fill_in_defaults=True))[source]¶
Bases:
UnstructureHandlerUnstructures a
NamedTupleinstance into adict.
- class compages.AsNamedTupleToList(options: ~compages._struct_like.StructLikeOptions = StructLikeOptions(to_unstructured_name=<function StructLikeOptions.<lambda>>, unstructure_skip_defaults=True, structure_fill_in_defaults=True))[source]¶
Bases:
UnstructureHandlerUnstructures a
NamedTupleinstance into alist.
- class compages.AsNone[source]¶
Bases:
UnstructureHandlerUnstructures
Noneas itself.
- class compages.AsStr[source]¶
Bases:
UnstructureHandlerUnstructures anything convertable to a
strasstr.
- class compages.AsTuple[source]¶
Bases:
UnstructureHandlerUnstructures as a
tuplegiven its type arguments.If the requested type is an unqalified
tuple, it is treated astuple[Any, ...].
- class compages.AsUnion[source]¶
Bases:
UnstructureHandlerAttempts to unstructure as every typr in the union in order, returns the result of the first succeeded call.
If none succeeded, raises a
UnstructuringError.
Errors¶
- class compages.StructuringError(message: str, inner_errors: list[tuple[StructField | UnionVariant | ListElem | DictKey | DictValue, StructuringError]] = [])[source]¶
An error during structuring.
Accumulates possible nested errors.
- class compages.UnstructuringError(message: str, inner_errors: list[tuple[StructField | UnionVariant | ListElem | DictKey | DictValue, UnstructuringError]] = [])[source]¶
An error during unstructuring.
Accumulates possible nested errors.