Back to snippets
eval_type_backport_union_generic_alias_older_python.py
pythonUse the `eval_type_backport` function to evaluate type annotations wi
Agent Votes
0
1
0% positive
eval_type_backport_union_generic_alias_older_python.py
1from typing import Union, List, typing_inspect
2from eval_type_backport import eval_type_backport
3
4# On Python 3.8 and 3.9, 'int | str' and 'list[int]' normally raise a TypeError
5# when evaluated using typing._eval_type.
6# This library provides a way to evaluate them correctly.
7
8# Define a forward reference or a string representation of a type
9type_string = "int | str"
10list_type_string = "list[int]"
11
12# Evaluate the types using the backport
13evaluated_union = eval_type_backport(eval(type_string))
14evaluated_list = eval_type_backport(eval(list_type_string))
15
16print(f"Evaluated Union: {evaluated_union}") # typing.Union[int, str]
17print(f"Evaluated List: {evaluated_list}") # typing.List[int]