Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix isinstance checks with PEP 604 unions containing None #17415

Merged
merged 1 commit into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7304,7 +7304,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
Loading