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

Consider overlap between instances and callables #17389

Merged
merged 2 commits into from
Jun 19, 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
18 changes: 16 additions & 2 deletions mypy/meet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from mypy.maptype import map_instance_to_supertype
from mypy.state import state
from mypy.subtypes import (
find_member,
is_callable_compatible,
is_equivalent,
is_proper_subtype,
Expand Down Expand Up @@ -477,9 +478,22 @@ def _type_object_overlap(left: Type, right: Type) -> bool:
ignore_pos_arg_names=True,
allow_partial_overlap=True,
)
elif isinstance(left, CallableType):

call = None
other = None
if isinstance(left, CallableType) and isinstance(right, Instance):
call = find_member("__call__", right, right, is_operator=True)
other = left
if isinstance(right, CallableType) and isinstance(left, Instance):
call = find_member("__call__", left, left, is_operator=True)
other = right
if isinstance(get_proper_type(call), FunctionLike):
assert call is not None and other is not None
return _is_overlapping_types(call, other)

if isinstance(left, CallableType):
left = left.fallback
elif isinstance(right, CallableType):
if isinstance(right, CallableType):
right = right.fallback

if isinstance(left, LiteralType) and isinstance(right, LiteralType):
Expand Down
35 changes: 35 additions & 0 deletions test-data/unit/check-statements.test
Original file line number Diff line number Diff line change
Expand Up @@ -2307,3 +2307,38 @@ class Outer:
class Inner:
break # E: "break" outside loop
[builtins fixtures/list.pyi]

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

class CAny:
def __call__(self) -> Any: ...
class CNone:
def __call__(self) -> None: ...
class CWrong:
def __call__(self, x: int) -> None: ...

def describe(func: Callable[[], None]) -> str:
if isinstance(func, CAny):
return "CAny"
elif isinstance(func, CNone):
return "CNone"
elif isinstance(func, CWrong):
return "CWrong" # E: Statement is unreachable
else:
return "other"

class C(CAny):
def __call__(self) -> None: ...

def f():
pass

describe(CAny())
describe(C())
describe(CNone())
describe(CWrong()) # E: Argument 1 to "describe" has incompatible type "CWrong"; expected "Callable[[], None]" \
# N: "CWrong.__call__" has type "Callable[[Arg(int, 'x')], None]"
describe(f)
[builtins fixtures/isinstancelist.pyi]
Loading