Skip to content

Commit e858d5d

Browse files
authored
Fix isinstance with unions of tuples (#20677)
1 parent 956e3ab commit e858d5d

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

mypy/checker.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8646,12 +8646,13 @@ def flatten(t: Expression) -> list[Expression]:
86468646
def flatten_types(t: Type) -> list[Type]:
86478647
"""Flatten a nested sequence of tuples into one list of nodes."""
86488648
t = get_proper_type(t)
8649+
if isinstance(t, UnionType):
8650+
return [b for a in t.items for b in flatten_types(a)]
86498651
if isinstance(t, TupleType):
86508652
return [b for a in t.items for b in flatten_types(a)]
86518653
elif is_named_instance(t, "builtins.tuple"):
86528654
return [t.args[0]]
8653-
else:
8654-
return [t]
8655+
return [t]
86558656

86568657

86578658
def expand_func(defn: FuncItem, map: dict[TypeVarId, Type]) -> FuncItem:

test-data/unit/check-isinstance.test

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2938,3 +2938,26 @@ def foo(x: object, t: type[Any]):
29382938
if isinstance(x, t):
29392939
reveal_type(x) # N: Revealed type is "Any"
29402940
[builtins fixtures/isinstance.pyi]
2941+
2942+
[case testIsInstanceUnionOfTuples]
2943+
# flags: --strict-equality --warn-unreachable
2944+
from __future__ import annotations
2945+
from typing import TypeVar, Iterator
2946+
2947+
T1 = TypeVar("T1")
2948+
T2 = TypeVar("T2")
2949+
T3 = TypeVar("T3")
2950+
2951+
def extract(
2952+
values: object,
2953+
ts: (
2954+
tuple[type[T1]]
2955+
| tuple[type[T1], type[T2]]
2956+
| tuple[type[T1], type[T2], type[T3]]
2957+
)
2958+
) -> Iterator[T1 | T2 | T3]:
2959+
if isinstance(values, ts):
2960+
reveal_type(values) # N: Revealed type is "T1`-1 | T2`-2 | T3`-3"
2961+
yield values
2962+
raise
2963+
[builtins fixtures/primitives.pyi]

0 commit comments

Comments
 (0)