Skip to content

Commit ac4cacb

Browse files
authored
Somewhat better support for isinstance on old-style unions (#19714)
Partially fixes #17680 , remainder of the issue should probably be fixed in the isinstance stub
1 parent 01e2a8c commit ac4cacb

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

mypy/checkexpr.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,10 @@ def visit_call_expr_inner(self, e: CallExpr, allow_none_return: bool = False) ->
582582
and not node.node.no_args
583583
and not (
584584
isinstance(union_target := get_proper_type(node.node.target), UnionType)
585-
and union_target.uses_pep604_syntax
585+
and (
586+
union_target.uses_pep604_syntax
587+
or self.chk.options.python_version >= (3, 10)
588+
)
586589
)
587590
):
588591
self.msg.type_arguments_not_allowed(e)

test-data/unit/check-unions.test

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1345,3 +1345,30 @@ x: Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11]
13451345
y: Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, None]
13461346
x = y # E: Incompatible types in assignment (expression has type "Union[C1, C2, C3, C4, C5, <6 more items>, None]", variable has type "Union[C1, C2, C3, C4, C5, <6 more items>]") \
13471347
# N: Item in the first union not in the second: "None"
1348+
1349+
[case testTypeAliasWithOldUnionIsInstance]
1350+
# flags: --python-version 3.10
1351+
from typing import Union
1352+
SimpleAlias = Union[int, str]
1353+
1354+
def foo(x: Union[int, str, tuple]):
1355+
# TODO: fix the typeshed stub for isinstance
1356+
if isinstance(x, SimpleAlias): # E: Argument 2 to "isinstance" has incompatible type "<typing special form>"; expected "type"
1357+
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str, builtins.tuple[Any, ...]]"
1358+
else:
1359+
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str, builtins.tuple[Any, ...]]"
1360+
[builtins fixtures/tuple.pyi]
1361+
1362+
1363+
[case testTypeAliasWithOldUnionIsInstancePython39]
1364+
# flags: --python-version 3.9
1365+
from typing import Union
1366+
SimpleAlias = Union[int, str]
1367+
1368+
def foo(x: Union[int, str, tuple]):
1369+
if isinstance(x, SimpleAlias): # E: Parameterized generics cannot be used with class or instance checks \
1370+
# E: Argument 2 to "isinstance" has incompatible type "<typing special form>"; expected "type"
1371+
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str, builtins.tuple[Any, ...]]"
1372+
else:
1373+
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str, builtins.tuple[Any, ...]]"
1374+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)