bagof.converters.common
Common converters (any, union, etc.).
Classes
ToAny
ToNone
ToType
ToUnion
Bases: Converter[TO, FROM]
Converter for Union.
None is preserved when the union contains a None branch.
Otherwise, converters for branches that already match the value
are tried before the remaining branches, in declaration order.
Matching a container's outer type still runs its element converters.
A narrower branch (a sub hint of a matched branch) with a refining
converter (refines=True, e.g. enums and literals) is tried before
matched branches. The first successful conversion wins.
Refinement
>>> import enum
>>> from typing import Union
>>> from bagof.converters import get_converter
>>> class Mode(str, enum.Enum):
... A = "a"
>>> convert = get_converter(Union[Mode, str])
>>> convert("a") # a str, but refined to the enum member
<Mode.A: 'a'>
>>> convert("zzz") # not a member: kept as a str
'zzz'
>>> get_converter(Union[bool, int])(1) # bool does not refine
1
Example
ToLiteral
ToTypeVar
ToAnnotated
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_metadata
classmethod
Register a converter class for use as Annotated
metadata.
Distinct from Converter.register, which registers a
converter for a type hint in the global registry; this one
registers it for a piece of Annotated metadata.
like
Return the like hint from the first converter in the chain.