Skip to content

[match-case] fix matching against typing.Callable and Protocol types. #19471

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 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
check if current_type is AnyType
  • Loading branch information
randolf-scholz committed Jul 20, 2025
commit 143f99034605558ab92451b04269dbcb4695565a
17 changes: 11 additions & 6 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7994,11 +7994,13 @@ def conditional_types(
) -> tuple[Type | None, Type | None]:
"""Takes in the current type and a proposed type of an expression.

Returns a 2-tuple: The first element is the proposed type, if the expression
can be the proposed type. The second element is the type it would hold
if it was not the proposed type, if any. UninhabitedType means unreachable.
None means no new information can be inferred. If default is set it is returned
instead."""
Returns a 2-tuple:
The first element is the proposed type, if the expression can be the proposed type.
The second element is the type it would hold if it was not the proposed type, if any.
UninhabitedType means unreachable.
None means no new information can be inferred.
If default is set it is returned instead.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Maybe this line shouldn't be separated from the previous one? Now it's a bit ambiguous whether default is returned instead of None only or instead of both None and Uninhabited

Copy link
Contributor Author

Choose a reason for hiding this comment

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

To be honest, I do not think this part of the docstring is really accurate to begin with. Looking at the code on the main branch

https://github.com/python/mypy/blob/c6b40df63ce0fecab6bced800ce778d99587c9b8/mypy/checker.py#L7990-
L8045

How about something like:

Returns a 2-tuple:
    The first element is the proposed type, if the expression can be the proposed type.
        (or default, if default is set and the expression is a subtype of the proposed type).
    The second element is the type it would hold if it was not the proposed type, if any.
        (or default, if default is set and the expression is not a subtype of the proposed type).

    UninhabitedType means unreachable.
    None means no new information can be inferred.

"""
if proposed_type_ranges:
if len(proposed_type_ranges) == 1:
target = proposed_type_ranges[0].item
Expand All @@ -8010,7 +8012,10 @@ def conditional_types(
current_type = try_expanding_sum_type_to_union(current_type, enum_name)
proposed_items = [type_range.item for type_range in proposed_type_ranges]
proposed_type = make_simplified_union(proposed_items)
if isinstance(proposed_type, AnyType):
current_type = get_proper_type(current_type)
if isinstance(current_type, AnyType):
return proposed_type, current_type
elif isinstance(proposed_type, AnyType):
# We don't really know much about the proposed type, so we shouldn't
# attempt to narrow anything. Instead, we broaden the expr to Any to
# avoid false positives
Expand Down
32 changes: 32 additions & 0 deletions test-data/unit/check-generic-alias.test
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,38 @@ t23: collections.abc.ValuesView[str]
# reveal_type(t23) # Nx Revealed type is "collections.abc.ValuesView[builtins.str]"
[builtins fixtures/tuple.pyi]

[case testGenericAliasIsinstanceUnreachable]
# flags: --warn-unreachable --python-version 3.10
from collections.abc import Iterable

class A: ...

def test(dependencies: list[A] | None) -> None:
if dependencies is None:
dependencies = []
elif not isinstance(dependencies, Iterable):
dependencies = [dependencies] # E: Statement is unreachable

[builtins fixtures/isinstancelist.pyi]
[typing fixtures/typing-full.pyi]

[case testGenericAliasRedundantExprCompoundIfExpr]
# flags: --warn-unreachable --enable-error-code=redundant-expr --python-version 3.10

from typing import Any, reveal_type
from collections.abc import Iterable

def test_example(x: Iterable[Any]) -> None:
if isinstance(x, Iterable) and not isinstance(x, str): # E: Left operand of "and" is always true
reveal_type(x) # N: Revealed type is "typing.Iterable[Any]"

def test_counterexample(x: Any) -> None:
if isinstance(x, Iterable) and not isinstance(x, str):
reveal_type(x) # N: Revealed type is "typing.Iterable[Any]"

[builtins fixtures/isinstancelist.pyi]
[typing fixtures/typing-full.pyi]


[case testGenericBuiltinTupleTyping]
from typing import Tuple
Expand Down
15 changes: 0 additions & 15 deletions test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -1086,21 +1086,6 @@ while bool():
x + 'a'
[builtins fixtures/isinstance.pyi]

[case testUnreachableCode3]
# flags: --warn-unreachable --python-version 3.10
from collections.abc import Iterable

class A: ...

def test(dependencies: list[A] | None) -> None:
if dependencies is None:
dependencies = []
elif not isinstance(dependencies, Iterable):
dependencies = [dependencies] # E: Statement is unreachable

[builtins fixtures/isinstancelist.pyi]
[typing fixtures/typing-full.pyi]

[case testUnreachableWhileTrue]
def f(x: int) -> None:
while True:
Expand Down
57 changes: 55 additions & 2 deletions test-data/unit/check-python310.test
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,30 @@ match m:
-- Literal Pattern --

[case testMatchLiteralPatternNarrows]
# flags: --warn-unreachable
m: object

match m:
case 1:
reveal_type(m) # N: Revealed type is "Literal[1]"
case 2:
reveal_type(m) # N: Revealed type is "Literal[2]"
case other:
reveal_type(other) # N: Revealed type is "builtins.object"

[case testMatchLiteralPatternNarrows2]
# flags: --warn-unreachable
from typing import Any

m: Any

match m:
case 1:
reveal_type(m) # N: Revealed type is "Literal[1]"
case 2:
reveal_type(m) # N: Revealed type is "Literal[2]"
case other:
reveal_type(other) # N: Revealed type is "Any"

[case testMatchLiteralPatternAlreadyNarrower-skip]
m: bool
Expand Down Expand Up @@ -1070,28 +1089,42 @@ match m:
pass

[case testMatchClassPatternCallable]
from typing import Callable
# flags: --warn-unreachable
from typing import Callable, Any

class FnImpl:
def __call__(self, x: object, /) -> int: ...

def test_any(x: Any) -> None:
match x:
case Callable() as fn:
reveal_type(fn) # N: Revealed type is "def (*Any, **Any) -> Any"
case other:
reveal_type(other) # N: Revealed type is "Any"

def test_object(x: object) -> None:
match x:
case Callable() as fn:
reveal_type(fn) # N: Revealed type is "def (*Any, **Any) -> Any"
case other:
reveal_type(other) # N: Revealed type is "builtins.object"

def test_impl(x: FnImpl) -> None:
match x:
case Callable() as fn:
reveal_type(fn) # N: Revealed type is "__main__.FnImpl"
case other:
reveal_type(other) # E: Statement is unreachable

def test_callable(x: Callable[[object], int]) -> None:
match x:
case Callable() as fn:
reveal_type(fn) # N: Revealed type is "def (builtins.object) -> builtins.int"

case other:
reveal_type(other) # E: Statement is unreachable

[case testMatchClassPatternCallbackProtocol]
# flags: --warn-unreachable
from typing import Any, Callable
from typing_extensions import Protocol, runtime_checkable

Expand All @@ -1102,24 +1135,38 @@ class FnProto(Protocol):
class FnImpl:
def __call__(self, x: object, /) -> int: ...

def test_any(x: Any) -> None:
match x:
case FnProto() as fn:
reveal_type(fn) # N: Revealed type is "__main__.FnProto"
case other:
reveal_type(other) # N: Revealed type is "Any"

def test_object(x: object) -> None:
match x:
case FnProto() as fn:
reveal_type(fn) # N: Revealed type is "__main__.FnProto"
case other:
reveal_type(other) # N: Revealed type is "builtins.object"

def test_impl(x: FnImpl) -> None:
match x:
case FnProto() as fn:
reveal_type(fn) # N: Revealed type is "__main__.FnImpl"
case other:
reveal_type(other) # E: Statement is unreachable

def test_callable(x: Callable[[object], int]) -> None:
match x:
case FnProto() as fn:
reveal_type(fn) # N: Revealed type is "def (builtins.object) -> builtins.int"
case other:
reveal_type(other) # E: Statement is unreachable

[builtins fixtures/dict.pyi]

[case testMatchClassPatternAnyCallableProtocol]
# flags: --warn-unreachable
from typing import Any, Callable
from typing_extensions import Protocol, runtime_checkable

Expand All @@ -1134,16 +1181,22 @@ def test_object(x: object) -> None:
match x:
case AnyCallable() as fn:
reveal_type(fn) # N: Revealed type is "__main__.AnyCallable"
case other:
reveal_type(other) # N: Revealed type is "builtins.object"

def test_impl(x: FnImpl) -> None:
match x:
case AnyCallable() as fn:
reveal_type(fn) # N: Revealed type is "__main__.FnImpl"
case other:
reveal_type(other) # E: Statement is unreachable

def test_callable(x: Callable[[object], int]) -> None:
match x:
case AnyCallable() as fn:
reveal_type(fn) # N: Revealed type is "def (builtins.object) -> builtins.int"
case other:
reveal_type(other) # E: Statement is unreachable

[builtins fixtures/dict.pyi]

Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy