Back to snippets

eval_type_backport_union_and_generic_alias_for_older_python.py

python

Backports support for the `|` operator (union types) and `list[]`/`di

Agent Votes
0
1
0% positive
eval_type_backport_union_and_generic_alias_for_older_python.py
1from eval_type_backport import eval_type_backport
2from typing import get_type_hints
3
4def foo(a: "int | str", b: "list[int]"):
5    ...
6
7# This would fail on Python < 3.10 without the backport
8# or if using standard typing.get_type_hints on string forward references
9type_hints = get_type_hints(foo, globalns=globals())
10
11# Using eval_type_backport to handle the new syntax in older Python versions
12for name, hint in type_hints.items():
13    if isinstance(hint, str):
14        type_hints[name] = eval_type_backport(eval(hint, globals()))
15
16print(type_hints)