Skip to content

Commit 6e85c32

Browse files
committed
Allow variables inside isinstance
1 parent 72967fd commit 6e85c32

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

mypy/checker.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2774,8 +2774,16 @@ def flatten(t: Expression) -> List[Expression]:
27742774
return [t]
27752775

27762776

2777+
def flatten_types(t: Type) -> List[Type]:
2778+
"""Flatten a nested sequence of tuples into one list of nodes."""
2779+
if isinstance(t, TupleType):
2780+
return [b for a in t.items for b in flatten_types(a)]
2781+
else:
2782+
return [t]
2783+
2784+
27772785
def get_isinstance_type(expr: Expression, type_map: Dict[Expression, Type]) -> List[TypeRange]:
2778-
all_types = [type_map[e] for e in flatten(expr)]
2786+
all_types = flatten_types(type_map[expr])
27792787
types = [] # type: List[TypeRange]
27802788
for type in all_types:
27812789
if isinstance(type, FunctionLike) and type.is_type_obj():

test-data/unit/check-isinstance.test

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1412,3 +1412,19 @@ def f(x: Union[int, A], a: Type[A]) -> None:
14121412

14131413
[builtins fixtures/isinstancelist.pyi]
14141414

1415+
1416+
[case testIsinstanceVariableSubstitution]
1417+
T = (int, str)
1418+
U = (list, T)
1419+
x: object = None
1420+
1421+
if isinstance(x, T):
1422+
reveal_type(x) # E: Revealed type is 'Union[builtins.int, builtins.str]'
1423+
1424+
if isinstance(x, U):
1425+
reveal_type(x) # E: Revealed type is 'Union[builtins.list[Any], builtins.int, builtins.str]'
1426+
1427+
if isinstance(x, (set, (list, T))):
1428+
reveal_type(x) # E: Revealed type is 'Union[builtins.set[Any], builtins.list[Any], builtins.int, builtins.str]'
1429+
1430+
[builtins fixtures/isinstancelist.pyi]

0 commit comments

Comments
 (0)