adaptix package

Subpackages

Submodules

Module contents

class adaptix.AdornedRetort(
*,
recipe: ~collections.abc.Iterable[~adaptix._internal.provider.essential.Provider] = (),
strict_coercion: bool = True,
debug_trail: ~adaptix._internal.definitions.DebugTrail = DebugTrail.ALL,
error_renderer: ~adaptix._internal.retort.error_renderer.ErrorRenderer | None = <adaptix._internal.retort.error_renderer.BuiltinErrorRenderer object>,
)

Bases: OperatingRetort

A retort implementing high-level user interface

dump(
data: Any,
tp: Any | None = None,
/,
) Any
extend(
*,
recipe: Iterable[Provider],
) AR
get_dumper(
tp: type[T],
) Callable[[T], Any]
get_loader(
tp: type[T],
) Callable[[Any], T]
load(
data: Any,
tp: Any,
/,
)
make_json_schema(
tp: Any,
ctx: JSONSchemaContext,
) JSONSchema
recipe: ClassVar[Iterable[Provider]]
replace(
*,
strict_coercion: bool | Omitted = Omitted(),
debug_trail: DebugTrail | Omitted = Omitted(),
error_renderer: ErrorRenderer | None | Omitted = Omitted(),
) AR
exception adaptix.AggregateCannotProvide(
message: str,
exceptions: Sequence[CannotProvide],
*,
is_terminal: bool = False,
is_demonstrative: bool = False,
parent_notes_gen: Callable[[], Sequence[str]] | None = None,
)

Bases: ExceptionGroup[CannotProvide], CannotProvide

derive(
excs: Sequence[CannotProvide],
) AggregateCannotProvide
derive_upcasting(
excs: Sequence[CannotProvide],
) CannotProvide

Same as method derive but allow passing an empty sequence

classmethod make(
message: str,
exceptions: Sequence[CannotProvide],
*,
is_terminal: bool = False,
is_demonstrative: bool = False,
parent_notes_gen: Callable[[], Sequence[str]] | None = None,
) CannotProvide
exception adaptix.CannotProvide(
message: str = '',
*,
is_terminal: bool = False,
is_demonstrative: bool = False,
parent_notes_gen: Callable[[], Sequence[str]] | None = None,
)

Bases: Exception

class adaptix.Chain(
value,
)

Bases: Enum

FIRST = 'FIRST'
LAST = 'LAST'
class adaptix.DebugTrail(
value,
)

Bases: Enum

DISABLE = 'DISABLE'
FIRST = 'FIRST'
ALL = 'ALL'
class adaptix.ExtraCollect

Bases: object

Collect extra data and pass it to object

class adaptix.ExtraForbid

Bases: object

Raise error if extra data would be met

class adaptix.ExtraKwargs

Bases: object

class adaptix.ExtraSkip

Bases: object

Ignore any extra data

class adaptix.FilledRetort(
*,
recipe: ~collections.abc.Iterable[~adaptix._internal.provider.essential.Provider] = (),
error_renderer: ~adaptix._internal.retort.error_renderer.ErrorRenderer | None = <adaptix._internal.retort.error_renderer.BuiltinErrorRenderer object>,
)

Bases: OperatingRetort, ABC

A retort contains builtin providers

recipe: ClassVar[Iterable[Provider]]
class adaptix.LocStackPattern(
stack: tuple[LocStackChecker, ...],
)

Bases: object

property ANY: AnyLocStackChecker
build_loc_stack_checker() LocStackChecker
generic_arg(
pos: int,
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
) Pat
class adaptix.Mediator

Bases: DirectMediator, ABC, Generic[ResponseT]

Mediator is an object that gives provider access to other providers and that stores the state of the current search.

Mediator is a proxy to providers of retort.

abstractmethod cached_call(
func: Callable[[...], T],
*args: Any,
**kwargs: Any,
) T
abstractmethod provide_from_next() ResponseT

Forward current request to providers that placed after current provider at the recipe.

class adaptix.NameStyle(
value,
)

Bases: Enum

An enumeration of different naming conventions

LOWER_SNAKE = 'lower_snake'
CAMEL_SNAKE = 'camel_Snake'
PASCAL_SNAKE = 'Pascal_Snake'
UPPER_SNAKE = 'UPPER_SNAKE'
LOWER_KEBAB = 'lower-kebab'
CAMEL_KEBAB = 'camel-Kebab'
PASCAL_KEBAB = 'Pascal-Kebab'
UPPER_KEBAB = 'UPPER-KEBAB'
LOWER = 'lowercase'
CAMEL = 'camelCase'
PASCAL = 'PascalCase'
UPPER = 'UPPERCASE'
LOWER_DOT = 'lower.dot'
CAMEL_DOT = 'camel.Dot'
PASCAL_DOT = 'Pascal.Dot'
UPPER_DOT = 'UPPER.DOT'
class adaptix.Omitted

Bases: object

class adaptix.Provider

Bases: ABC

An object that can process Request instances

abstractmethod get_request_handlers() Sequence[tuple[type[Request], RequestChecker, Callable[[Mediator[ResponseT], RequestT], ResponseT]]]
exception adaptix.ProviderNotFoundError(
message: str,
description: str | None = None,
)

Bases: Exception

class adaptix.Request

Bases: Generic[T]

An object that contains data to be processed by Provider.

Generic argument indicates which object should be returned after request processing.

Request must always be a hashable object

class adaptix.Retort(
*,
recipe: ~collections.abc.Iterable[~adaptix._internal.provider.essential.Provider] = (),
strict_coercion: bool = True,
debug_trail: ~adaptix._internal.definitions.DebugTrail = DebugTrail.ALL,
error_renderer: ~adaptix._internal.retort.error_renderer.ErrorRenderer | None = <adaptix._internal.retort.error_renderer.BuiltinErrorRenderer object>,
)

Bases: FilledRetort, AdornedRetort

recipe: ClassVar[Iterable[Provider]]
adaptix.TypeHint

alias of Any

adaptix.as_is_dumper(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
) Provider

Provider that creates dumper which does nothing with input data.

Parameters:

pred – Predicate specifying where dumper should be used. See Predicate system for details.

Returns:

Desired provider

adaptix.as_is_loader(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
) Provider

Provider that creates loader which does nothing with input data.

Parameters:

pred – Predicate specifying where loader should be used. See Predicate system for details.

Returns:

Desired provider

adaptix.as_sentinel(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
) Provider

Mark the type as a sentinel. Sentinels are not meant to be represented externally. They serve to differentiate a missing field from one explicitly set to None (null).

If a field in the model is a union type that includes a sentinel, it must have a default value set to that sentinel. Additionally, the name_mapping.omit_default option must be enabled.

When these conditions are met, if a field is missing during loading, the class instance will receive the sentinel value. This makes it possible to distinguish a missing field from one explicitly set to null. When dumping data, fields with sentinel values will be omitted.

Sentinel types only can be used within a union. They do not have loaders or dumpers, as they are not intended to appear in external data.

Parameters:

pred – Predicate specifying where the provider should be used. See Predicate system for details.

adaptix.bound(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
provider: Provider,
) Provider
adaptix.constructor(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
func: Callable,
) Provider
adaptix.create_loc_stack_checker(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
) LocStackChecker
adaptix.date_by_timestamp(
pred: str | ~re.Pattern | type | ~typing.Any | ~adaptix._internal.provider.loc_stack_filtering.LocStackChecker | ~adaptix._internal.provider.loc_stack_filtering.LocStackPattern = <adaptix._internal.provider.loc_stack_filtering.AnyLocStackChecker object>,
) Provider

Provider that can load date object from UNIX timestamp. Note that date objects can`t be dumped to the UNIX timestamp

Parameters:

pred – Predicate specifying where the provider should be used. See Predicate system for details.

adaptix.datetime_by_format(
pred: str | ~re.Pattern | type | ~typing.Any | ~adaptix._internal.provider.loc_stack_filtering.LocStackChecker | ~adaptix._internal.provider.loc_stack_filtering.LocStackPattern = <adaptix._internal.provider.loc_stack_filtering.AnyLocStackChecker object>,
*,
fmt: str,
) Provider

Provider that can load/dump datetime object from/to format string e.g “%d/%m/%y %H:%M”

Parameters:
  • pred – Predicate specifying where the provider should be used. See Predicate system for details.

  • fmt – format parameter which will be passed to datetime.strptime method.

adaptix.datetime_by_timestamp(
pred: str | ~re.Pattern | type | ~typing.Any | ~adaptix._internal.provider.loc_stack_filtering.LocStackChecker | ~adaptix._internal.provider.loc_stack_filtering.LocStackPattern = <adaptix._internal.provider.loc_stack_filtering.AnyLocStackChecker object>,
*,
tz: ~datetime.timezone | None = datetime.timezone.utc,
) Provider

Provider that can load/dump datetime object from/to UNIX timestamp.

Parameters:
  • pred – Predicate specifying where the provider should be used. See Predicate system for details.

  • tz – tz parameter which will be passed to the datetime.fromtimestamp method.

adaptix.default_dict(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
default_factory: Callable,
) Provider

Provider for defaultdict class

Parameters:
  • pred – Predicate specifying where the provider should be used. See Predicate system for details.

  • default_factory – default_factory parameter of the defaultdict instance to be created by the loader

adaptix.dump(
data: Any,
tp: Any | None = None,
/,
) Any
adaptix.dumper(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
func: adaptix.Dumper,
chain: Chain | None = None,
*,
json_schema: JSONSchema | KeepJSONSchema | EraseJSONSchema | JSONSchemaPatch = EraseJSONSchema(),
) Provider

Basic provider to define custom dumper.

Parameters:
  • pred – Predicate specifying where dumper should be used. See Predicate system for details.

  • func – Function that acts as dumper. It must take one positional argument of raw data and return the processed value.

  • chain

    Controls how the function will interact with the previous dumper.

    When None is passed, the specified function will fully replace the previous dumper.

    If a parameter is Chain.FIRST, the specified function will take raw data and its result will be passed to previous dumper.

    If the parameter is Chain.LAST, the specified function gets result of the previous dumper.

  • json_schema – JSON schema value associated with the dumper. By default, when the loader is overridden, the previous schema is erased. You can preserve the existing schema by using KeepJSONSchema(), pass your own schema or patch the previous schema.

Returns:

Desired provider

adaptix.enum_by_exact_value(
*preds: Any | str | EnumType | LocStackPattern,
) Provider

Provider that represents enum members to the outside world by their value without any processing.

Parameters:

preds – Predicates specifying where the provider should be used. The provider will be applied if any predicates meet the conditions, if no predicates are passed, the provider will be used for all Enums. See Predicate system for details.

Returns:

Desired provider

adaptix.enum_by_name(
*preds: Any | str | EnumType | LocStackPattern,
name_style: NameStyle | None = None,
map: Mapping[str | Enum, str] | None = None,
) Provider

Provider that represents enum members to the outside world by their name.

Parameters:
  • preds – Predicates specifying where the provider should be used. The provider will be applied if any predicates meet the conditions, if no predicates are passed, the provider will be used for all Enums. See Predicate system for details.

  • name_style – Name style for representing members to the outside world. If it is set, the provider will automatically convert the names of enum members to the specified convention.

  • map – Mapping for representing members to the outside world. If it is set, the provider will use it to rename members individually; its keys can either be member names as strings or member instances.

Returns:

Desired provider

adaptix.enum_by_value(
first_pred: Any | str | EnumType | LocStackPattern,
/,
*preds: Any | str | EnumType | LocStackPattern,
tp: Any,
) Provider

Provider that represents enum members to the outside world by their value by loader and dumper of specified type. The loader will call the loader of the tp and pass it to the enum constructor. The dumper will get value from eum member and pass it to the dumper of the tp.

Parameters:
  • first_pred – Predicate specifying where the provider should be used. See Predicate system for details.

  • preds – Additional predicates. The provider will be applied if any predicates meet the conditions.

  • tp – Type of enum members. This type must cover all enum members for the correct operation of loader and dumper

Returns:

Desired provider

adaptix.flag_by_exact_value(
*preds: Any | str | EnumType | LocStackPattern,
) Provider

Provider that represents flag members to the outside world by their value without any processing. It does not support flags with skipped bits and negative values (it is recommended to use enum.auto() to define flag values instead of manually specifying them).

Parameters:

preds – Predicates specifying where the provider should be used. The provider will be applied if any predicates meet the conditions, if no predicates are passed, the provider will be used for all Flags. See Predicate system for details.

Returns:

Desired provider

adaptix.flag_by_member_names(
*preds: Any | str | EnumType | LocStackPattern,
allow_single_value: bool = False,
allow_duplicates: bool = True,
allow_compound: bool = True,
name_style: NameStyle | None = None,
map: Mapping[str | Enum, str] | None = None,
) Provider

Provider that represents flag members to the outside world by list of their names.

Loader takes a flag members name list and returns united flag member (given members combined by operator |, namely bitwise or).

Dumper takes a flag member and returns a list of names of flag members, included in the given flag member.

Parameters:
  • preds – Predicates specifying where the provider should be used. The provider will be applied if any predicates meet the conditions, if no predicates are passed, the provider will be used for all Flags. See Predicate system for details.

  • allow_single_value – Allows calling the loader with a single value. If this is allowed, singular values are treated as one element list.

  • allow_duplicates – Allows calling the loader with a list containing non-unique elements. Unless this is allowed, loader will raise DuplicatedValuesLoadError in that case.

  • allow_compound – Allows the loader to accept names of compound members (e.g. WHITE = RED | GREEN | BLUE) and the dumper to return names of compound members. If this is allowed, dumper will use compound members names to serialize value.

  • name_style – Name style for representing members to the outside world. If it is set, the provider will automatically convert the names of all flag members to the specified convention.

  • map – Mapping for representing members to the outside world. If it is set, the provider will use it to rename members individually; its keys can either be member names as strings or member instances.

Returns:

Desired provider

adaptix.load(
data: Any,
tp: Any,
/,
)
adaptix.loader(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
func: adaptix.Loader,
chain: Chain | None = None,
*,
json_schema: JSONSchema | KeepJSONSchema | EraseJSONSchema | JSONSchemaPatch = EraseJSONSchema(),
) Provider

Basic provider to define custom loader.

Parameters:
  • pred – Predicate specifying where loader should be used. See Predicate system for details.

  • func – Function that acts as loader. It must take one positional argument of raw data and return the processed value.

  • chain

    Controls how the function will interact with the previous loader.

    When None is passed, the specified function will fully replace the previous loader.

    If a parameter is Chain.FIRST, the specified function will take raw data and its result will be passed to previous loader.

    If the parameter is Chain.LAST, the specified function gets result of the previous loader.

  • json_schema – JSON schema value associated with the loader. By default, when the loader is overridden, the previous schema is erased. You can preserve the existing schema by using KeepJSONSchema(), pass your own schema or patch the previous schema.

Returns:

Desired provider

adaptix.name_mapping(
pred: Omittable[Pred] = Omitted(),
*,
skip: Omittable[Iterable[Pred] | Pred] = Omitted(),
only: Omittable[Iterable[Pred] | Pred] = Omitted(),
map: Omittable[NameMap] = Omitted(),
as_list: Omittable[bool] = Omitted(),
trim_trailing_underscore: Omittable[bool] = Omitted(),
name_style: Omittable[NameStyle | None] = Omitted(),
omit_default: Omittable[Iterable[Pred] | Pred | bool] = Omitted(),
extra_in: Omittable[ExtraIn] = Omitted(),
extra_out: Omittable[ExtraOut] = Omitted(),
chain: Chain | None = Chain.FIRST,
) Provider

A name mapping decides which fields will be presented to the outside world and how they will look.

The mapping process consists of two stages: 1. Determining which fields are presented 2. Mutating names of presented fields

skip parameter has higher priority than only.

Mutating parameters works in that way: Mapper tries to use the value from the map. If the field is not presented in the map, trim trailing underscore and convert name style.

The field must follow snake_case to could be converted.

Parameters:
adaptix.validator(
pred: str | Pattern | type | Any | LocStackChecker | LocStackPattern,
func: Callable[[Any], bool],
error: str | Callable[[Any], LoadError] | None = None,
chain: Chain = Chain.LAST,
) Provider
adaptix.with_property(
pred: Pred,
prop: str | property,
tp: Omittable[TypeHint] = Omitted(),
/,
*,
default: Default = NoDefault(),
access_error: Catchable | None = None,
metadata: Mapping[Any, Any] = mappingproxy({}),
) Provider

Provider registering property for a model for dumping. This property will be treated as a usual field, so it can be mapped or skipped.

Parameters:
  • pred – Predicate specifying class to add property. See Predicate system for details.

  • prop – A property to register. It can be a string representing attribute name or property object. The property object will be converted to attribute name via prop.fget.__name__

  • tp – Output type of property. By default, this type is inferred from a property object of concrete class. If getter function has no specified return type, it will be supposed as Any.

  • default – A default value for this field.

  • access_error – Omit field when such error is raised. This will mark the field as optional.

  • metadata – Additional metadata of the field.