Skip to content

Commit

Permalink
Fix isinstance checks with PEP 604 unions containing None (#17415)
Browse files Browse the repository at this point in the history
Fixes #17413
  • Loading branch information
hauntsaninja authored Jun 21, 2024
1 parent f9d8f3a commit de4e9d6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7316,7 +7316,11 @@ def is_writable_attribute(self, node: Node) -> bool:
def get_isinstance_type(self, expr: Expression) -> list[TypeRange] | None:
if isinstance(expr, OpExpr) and expr.op == "|":
left = self.get_isinstance_type(expr.left)
if left is None and is_literal_none(expr.left):
left = [TypeRange(NoneType(), is_upper_bound=False)]
right = self.get_isinstance_type(expr.right)
if right is None and is_literal_none(expr.right):
right = [TypeRange(NoneType(), is_upper_bound=False)]
if left is None or right is None:
return None
return left + right
Expand Down
11 changes: 11 additions & 0 deletions test-data/unit/check-union-or-syntax.test
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,17 @@ isinstance(5, str | list[str])
isinstance(5, ParameterizedAlias)
[builtins fixtures/type.pyi]

[case testIsInstanceUnionNone]
# flags: --python-version 3.10
def foo(value: str | bool | None):
assert not isinstance(value, str | None)
reveal_type(value) # N: Revealed type is "builtins.bool"

def bar(value: object):
assert isinstance(value, str | None)
reveal_type(value) # N: Revealed type is "Union[builtins.str, None]"
[builtins fixtures/type.pyi]


# TODO: Get this test to pass
[case testImplicit604TypeAliasWithCyclicImportNotInStub-xfail]
Expand Down

0 comments on commit de4e9d6

Please sign in to comment.