Skip to content

Commit bf89ff9

Browse files
authored
bpo-44490: Improve typing module compatibility with types.Union (GH-27048)
1 parent f783428 commit bf89ff9

File tree

5 files changed

+40
-7
lines changed

5 files changed

+40
-7
lines changed

Lib/test/ann_module.py

+2
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,5 @@ def dec(func):
5858
def wrapper(*args, **kwargs):
5959
return func(*args, **kwargs)
6060
return wrapper
61+
62+
u: int | float

Lib/test/test_grammar.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ class CC(metaclass=CMeta):
473473
def test_var_annot_module_semantics(self):
474474
self.assertEqual(test.__annotations__, {})
475475
self.assertEqual(ann_module.__annotations__,
476-
{1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int]})
476+
{1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int], 'u': int | float})
477477
self.assertEqual(ann_module.M.__annotations__,
478478
{'123': 123, 'o': type})
479479
self.assertEqual(ann_module2.__annotations__, {})

Lib/test/test_typing.py

+21-1
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,8 @@ def test_repr(self):
315315
self.assertEqual(repr(u), 'typing.Union[typing.List[int], int]')
316316
u = Union[list[int], dict[str, float]]
317317
self.assertEqual(repr(u), 'typing.Union[list[int], dict[str, float]]')
318+
u = Union[int | float]
319+
self.assertEqual(repr(u), 'typing.Union[int, float]')
318320

319321
def test_cannot_subclass(self):
320322
with self.assertRaises(TypeError):
@@ -1449,6 +1451,8 @@ def test_basics(self):
14491451
with self.assertRaises(TypeError):
14501452
issubclass(SM1, SimpleMapping)
14511453
self.assertIsInstance(SM1(), SimpleMapping)
1454+
T = TypeVar("T")
1455+
self.assertEqual(List[list[T] | float].__parameters__, (T,))
14521456

14531457
def test_generic_errors(self):
14541458
T = TypeVar('T')
@@ -1785,6 +1789,7 @@ def test_extended_generic_rules_repr(self):
17851789
def test_generic_forward_ref(self):
17861790
def foobar(x: List[List['CC']]): ...
17871791
def foobar2(x: list[list[ForwardRef('CC')]]): ...
1792+
def foobar3(x: list[ForwardRef('CC | int')] | int): ...
17881793
class CC: ...
17891794
self.assertEqual(
17901795
get_type_hints(foobar, globals(), locals()),
@@ -1794,6 +1799,10 @@ class CC: ...
17941799
get_type_hints(foobar2, globals(), locals()),
17951800
{'x': list[list[CC]]}
17961801
)
1802+
self.assertEqual(
1803+
get_type_hints(foobar3, globals(), locals()),
1804+
{'x': list[CC | int] | int}
1805+
)
17971806

17981807
T = TypeVar('T')
17991808
AT = Tuple[T, ...]
@@ -2467,6 +2476,12 @@ def foo(a: Union['T']):
24672476
self.assertEqual(get_type_hints(foo, globals(), locals()),
24682477
{'a': Union[T]})
24692478

2479+
def foo(a: tuple[ForwardRef('T')] | int):
2480+
pass
2481+
2482+
self.assertEqual(get_type_hints(foo, globals(), locals()),
2483+
{'a': tuple[T] | int})
2484+
24702485
def test_tuple_forward(self):
24712486

24722487
def foo(a: Tuple['T']):
@@ -2848,7 +2863,7 @@ def test_get_type_hints_from_various_objects(self):
28482863
gth(None)
28492864

28502865
def test_get_type_hints_modules(self):
2851-
ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str}
2866+
ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str, 'u': int | float}
28522867
self.assertEqual(gth(ann_module), ann_module_type_hints)
28532868
self.assertEqual(gth(ann_module2), {})
28542869
self.assertEqual(gth(ann_module3), {})
@@ -4390,6 +4405,9 @@ def test_no_paramspec_in__parameters__(self):
43904405
self.assertNotIn(P, list[P].__parameters__)
43914406
self.assertIn(T, tuple[T, P].__parameters__)
43924407

4408+
self.assertNotIn(P, (list[P] | int).__parameters__)
4409+
self.assertIn(T, (tuple[T, P] | int).__parameters__)
4410+
43934411
def test_paramspec_in_nested_generics(self):
43944412
# Although ParamSpec should not be found in __parameters__ of most
43954413
# generics, they probably should be found when nested in
@@ -4399,8 +4417,10 @@ def test_paramspec_in_nested_generics(self):
43994417
C1 = Callable[P, T]
44004418
G1 = List[C1]
44014419
G2 = list[C1]
4420+
G3 = list[C1] | int
44024421
self.assertEqual(G1.__parameters__, (P, T))
44034422
self.assertEqual(G2.__parameters__, (P, T))
4423+
self.assertEqual(G3.__parameters__, (P, T))
44044424

44054425

44064426
class ConcatenateTests(BaseTestCase):

Lib/typing.py

+13-5
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ def _type_repr(obj):
196196
return repr(obj)
197197

198198

199-
def _collect_type_vars(types, typevar_types=None):
199+
def _collect_type_vars(types_, typevar_types=None):
200200
"""Collect all type variable contained
201201
in types in order of first appearance (lexicographic order). For example::
202202
@@ -205,10 +205,10 @@ def _collect_type_vars(types, typevar_types=None):
205205
if typevar_types is None:
206206
typevar_types = TypeVar
207207
tvars = []
208-
for t in types:
208+
for t in types_:
209209
if isinstance(t, typevar_types) and t not in tvars:
210210
tvars.append(t)
211-
if isinstance(t, (_GenericAlias, GenericAlias)):
211+
if isinstance(t, (_GenericAlias, GenericAlias, types.Union)):
212212
tvars.extend([t for t in t.__parameters__ if t not in tvars])
213213
return tuple(tvars)
214214

@@ -315,12 +315,14 @@ def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
315315
"""
316316
if isinstance(t, ForwardRef):
317317
return t._evaluate(globalns, localns, recursive_guard)
318-
if isinstance(t, (_GenericAlias, GenericAlias)):
318+
if isinstance(t, (_GenericAlias, GenericAlias, types.Union)):
319319
ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)
320320
if ev_args == t.__args__:
321321
return t
322322
if isinstance(t, GenericAlias):
323323
return GenericAlias(t.__origin__, ev_args)
324+
if isinstance(t, types.Union):
325+
return functools.reduce(operator.or_, ev_args)
324326
else:
325327
return t.copy_with(ev_args)
326328
return t
@@ -1009,7 +1011,7 @@ def __getitem__(self, params):
10091011
for arg in self.__args__:
10101012
if isinstance(arg, self._typevar_types):
10111013
arg = subst[arg]
1012-
elif isinstance(arg, (_GenericAlias, GenericAlias)):
1014+
elif isinstance(arg, (_GenericAlias, GenericAlias, types.Union)):
10131015
subparams = arg.__parameters__
10141016
if subparams:
10151017
subargs = tuple(subst[x] for x in subparams)
@@ -1775,6 +1777,12 @@ def _strip_annotations(t):
17751777
if stripped_args == t.__args__:
17761778
return t
17771779
return GenericAlias(t.__origin__, stripped_args)
1780+
if isinstance(t, types.Union):
1781+
stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1782+
if stripped_args == t.__args__:
1783+
return t
1784+
return functools.reduce(operator.or_, stripped_args)
1785+
17781786
return t
17791787

17801788

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:mod:`typing` now searches for type parameters in ``types.Union`` objects.
2+
``get_type_hints`` will also properly resolve annotations with nested
3+
``types.Union`` objects. Patch provided by Yurii Karabas.

0 commit comments

Comments
 (0)