future
¶
Utilities for maintaining runtime compatibility with emerging type annotation operations.
Notes
This module's functionality is unnecessary for Python versions >= 3.10
Typical Usage
>>> from typelib.py import future
>>> future.transform_annotation("str | int")
'typing.Union[str, int]'
>>> future.transform_annotation("dict[str, int]")
'typing.Dict[str, int]'
TransformAnnotation
¶
TransformAnnotation(union: str = 'typing.Union')
Bases: NodeTransformer
A ast.NodeTransformer
that transforms typing.Union
.
Source code in src/typelib/py/future.py
visit_BinOp
¶
visit_BinOp(node: BinOp)
Transform a ast.BinOp
to typing.Union
.
Source code in src/typelib/py/future.py
visit_Name
¶
visit_Name(node: Name)
Transform a builtin ast.Name
to the typing
equivalent.
Source code in src/typelib/py/future.py
visit_Subscript
¶
visit_Subscript(node: Subscript)
Transform all subscripts within a ast.Subscript
.
Source code in src/typelib/py/future.py
visit_Tuple
¶
visit_Tuple(node: Tuple)
Transform all values within a ast.Tuple
.
Source code in src/typelib/py/future.py
transform
cached
¶
Transform a modern annotations into their typing
equivalent:
types.UnionType
into atyping.Union
(str | int
->typing.Union[str, int]
)- builtin generics into typing generics (
dict[str, int]
->typing.Dict[str, int]
)
Parameters:
-
annotation
(str
) –The annotation to transform, as a string.
-
union
(str
, default:'typing.Union'
) –The name of the Union type to subscript (defaults
"typing.Union"
).
Note
While this transformation requires your expression be valid Python syntax, it doesn't make sure the type annotation is valid.