Skip to content

bagof.converters.common

Common converters (any, union, etc.).

Classes

ToAny

ToAny(hint: Any = UNSET, compose: bool = False)

Bases: Converter[TO, FROM]

Converter for Any (no-op, returns the value as-is).

Methods:

__call__
__call__(value: FROM) -> TO

Return the value unchanged.

ToNone

ToNone(hint: Any = UNSET, compose: bool = False)

Bases: Converter[NONE, Any]

Converter for None.

Methods:

__call__
__call__(value: Any) -> NONE

Return the value if it is None, otherwise raise a TypeError.

ToType

ToType(hint: Any = UNSET, compose: bool = False)

Bases: Converter[TO, FROM]

Converter for type and Type[T].

Note

This is a validating converter: it does not coerce, it checks that the value is a class (and, for Type[T], a subclass of T).

Methods:

__call__
__call__(value: FROM) -> TO

Return the value if it is a (sufficiently specific) type.

ToUnion

ToUnion(hint: Any = UNSET, compose: bool = False)

Bases: Converter[TO, FROM]

Converter for Union.

Example

Branches are tried in order; the first that converts wins:

>>> from bagof.converters import get_converter
>>> convert = get_converter(int | str)
>>> convert("5")
5
>>> convert("x")
'x'

Methods:

like
like(__reentrant: tuple = ()) -> Any

Return the union of the like hints for each union branch.

__call__
__call__(value: FROM) -> TO

Try each branch of the union in order; raise if none succeeds.

ToLiteral

ToLiteral(hint: Any = UNSET, compose: bool = False)

Bases: Converter[TO, FROM]

Converter for Literal.

Methods:

like
like(__reentrant: tuple = ()) -> Any

Return the literal hint itself.

__call__
__call__(value: FROM) -> TO

Return the value if it is one of the literals; raise otherwise.

ToTypeVar

ToTypeVar(hint: Any = UNSET, compose: bool = False)

Bases: Converter[TO, FROM]

Converter for TypeVar.

Methods:

like
like(__reentrant: tuple = ()) -> Any

Return the like hint for the unwrapped TypeVar bound.

__call__
__call__(value: FROM) -> TO

Delegate to the converter for the unwrapped TypeVar.

ToAnnotated

ToAnnotated(hint: Any = UNSET, compose: bool = False)

Bases: Converter[TO, FROM]

Converter for Annotated.

Note

Annotated converters look for converters in the metadata of an annotated type hint and apply them in sequence (if they are composable).

Attributes

converters property
converters: tuple[Converter, ...]

The chain of converters derived from the Annotated metadata.

Methods:

register classmethod
register(*hints: Unpack[tuple[Any]]) -> ClassDecorator

Register a converter class for use as Annotated metadata.

Example

@ToAnnotated.register(re.Pattern)
class ToRegexMatch(ToString):
    ...
like
like(__reentrant: tuple = ()) -> Any

Return the like hint from the first converter in the chain.

__call__
__call__(value: FROM) -> TO

Apply each converter in the chain in sequence.