8000 Narrow `is` with final types correctly by sobolevn · Pull Request #15646 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Narrow is with final types correctly #15646

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Address primer output
  • Loading branch information
sobolevn committed Jul 12, 2023
commit a0308bcde13e907e6dd0139f031df9956913bdd1
6 changes: 6 additions & 0 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1782,6 +1782,12 @@ def covers_at_runtime(item: Type, supertype: Type) -> bool:
item = get_proper_type(item)
supertype = get_proper_type(supertype)

# Left `Any` or `Type[Any]` type will never be covered at runtime:
if isinstance(item, AnyType) or (
isinstance(item, TypeType) and isinstance(item.item, AnyType)
):
return False

if isinstance(item, (CallableType, TypeType)) and item.is_singleton_type():

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if the RHS of the is operator is a specialized generic class like list[int]? The is conditional will always evaluate to False then.

if is_proper_subtype(item, supertype):
return True
Expand Down
22 changes: 22 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -1327,6 +1327,28 @@ else:
[builtins fixtures/isinstancelist.pyi]


[case testNarrowingAnyAgainstFinalType]
from typing import Type, Any
from typing_extensions import final

@final
class Mark: ...

x: Any
if x is Mark:
reveal_type(x) # N: Revealed type is "def () -> __main__.Mark"
else:
reveal_type(x) # N: Revealed type is "Any"

y: Type[Any]
if y is Mark:
reveal_type(y) # N: Revealed type is "Type[__main__.Mark]"
else:
reveal_type(y) # N: Revealed type is "Type[Any]"

[builtins fixtures/isinstancelist.pyi]


[case testNarrowingIsRegualType]
from typing import Type, Union

Expand Down
0