Skip to content

Commit de4e9d6

Browse files
authored
Fix isinstance checks with PEP 604 unions containing None (#17415)
Fixes #17413
1 parent f9d8f3a commit de4e9d6

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

mypy/checker.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7316,7 +7316,11 @@ def is_writable_attribute(self, node: Node) -> bool:
73167316
def get_isinstance_type(self, expr: Expression) -> list[TypeRange] | None:
73177317
if isinstance(expr, OpExpr) and expr.op == "|":
73187318
left = self.get_isinstance_type(expr.left)
7319+
if left is None and is_literal_none(expr.left):
7320+
left = [TypeRange(NoneType(), is_upper_bound=False)]
73197321
right = self.get_isinstance_type(expr.right)
7322+
if right is None and is_literal_none(expr.right):
7323+
right = [TypeRange(NoneType(), is_upper_bound=False)]
73207324
if left is None or right is None:
73217325
return None
73227326
return left + right

test-data/unit/check-union-or-syntax.test

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,17 @@ isinstance(5, str | list[str])
226226
isinstance(5, ParameterizedAlias)
227227
[builtins fixtures/type.pyi]
228228

229+
[case testIsInstanceUnionNone]
230+
# flags: --python-version 3.10
231+
def foo(value: str | bool | None):
232+
assert not isinstance(value, str | None)
233+
reveal_type(value) # N: Revealed type is "builtins.bool"
234+
235+
def bar(value: object):
236+
assert isinstance(value, str | None)
237+
reveal_type(value) # N: Revealed type is "Union[builtins.str, None]"
238+
[builtins fixtures/type.pyi]
239+
229240

230241
# TODO: Get this test to pass
231242
[case testImplicit604TypeAliasWithCyclicImportNotInStub-xfail]

0 commit comments

Comments
 (0)