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

Disallow assignment of protocol or abstract classes to Callable #18347

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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: 3 additions & 1 deletion mypy/erasetype.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,13 @@ def visit_unpack_type(self, t: UnpackType) -> ProperType:
def visit_callable_type(self, t: CallableType) -> ProperType:
# We must preserve the fallback type for overload resolution to work.
any_type = AnyType(TypeOfAny.special_form)
# If we're a type object, make sure we continue to be a valid type object
ret_type = t.ret_type if t.is_type_obj() else any_type
return CallableType(
arg_types=[any_type, any_type],
arg_kinds=[ARG_STAR, ARG_STAR2],
arg_names=[None, None],
ret_type=any_type,
ret_type=ret_type,
fallback=t.fallback,
is_ellipsis_args=True,
implicit=True,
Expand Down
2 changes: 1 addition & 1 deletion mypy/meet.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ def _type_object_overlap(left: Type, right: Type) -> bool:
def is_overlapping_erased_types(
left: Type, right: Type, *, ignore_promotions: bool = False
) -> bool:
"""The same as 'is_overlapping_erased_types', except the types are erased first."""
"""The same as 'is_overlapping_types', except the types are erased first."""
return is_overlapping_types(
erase_type(left),
erase_type(right),
Expand Down
5 changes: 5 additions & 0 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1533,6 +1533,11 @@ def g(x: int) -> int: ...
if right.is_type_obj() and not left.is_type_obj() and not allow_partial_overlap:
return False

if left.is_type_obj():
left_type_obj = left.type_object()
if (left_type_obj.is_protocol or left_type_obj.is_abstract) and not right.is_type_obj():
return False

# A callable L is a subtype of a generic callable R if L is a
# subtype of every type obtained from R by substituting types for
# the variables of R. We can check this by simply leaving the
Expand Down
2 changes: 1 addition & 1 deletion mypy/test/testtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ def test_erase_with_type_object(self) -> None:
arg_types=[self.fx.anyt, self.fx.anyt],
arg_kinds=[ARG_STAR, ARG_STAR2],
arg_names=[None, None],
ret_type=self.fx.anyt,
ret_type=self.fx.b,
fallback=self.fx.type_type,
),
)
Expand Down
3 changes: 2 additions & 1 deletion mypy/typeshed/stdlib/typing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ else:
_F = TypeVar("_F", bound=Callable[..., Any])
_P = _ParamSpec("_P")
_T = TypeVar("_T")
_FT = TypeVar("_FT", bound=Callable[..., Any] | type)

# These type variables are used by the container types.
_S = TypeVar("_S")
Expand All @@ -346,7 +347,7 @@ def no_type_check(arg: _F) -> _F: ...
def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ...

# This itself is only available during type checking
def type_check_only(func_or_cls: _F) -> _F: ...
def type_check_only(func_or_cls: _FT) -> _FT: ...

# Type aliases and type constructors

Expand Down
21 changes: 21 additions & 0 deletions test-data/unit/check-abstract.test
Original file line number Diff line number Diff line change
Expand Up @@ -1687,3 +1687,24 @@ from typing import TYPE_CHECKING
class C:
if TYPE_CHECKING:
def dynamic(self) -> int: ... # OK

[case testAbstractCallableSubtyping]
import abc
from typing import Callable, Protocol

class Proto(Protocol):
def meth(self): ...

def foo(t: Callable[..., Proto]):
t()

foo(Proto) # E: Argument 1 to "foo" has incompatible type "Type[Proto]"; expected "Callable[..., Proto]"

class Abstract(abc.ABC):
@abc.abstractmethod
def meth(self): ...

def bar(t: Callable[..., Abstract]):
t()

bar(Abstract) # E: Argument 1 to "bar" has incompatible type "Type[Abstract]"; expected "Callable[..., Abstract]"
3 changes: 2 additions & 1 deletion test-data/unit/check-functools.test
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,8 @@ def f1(cls: type[A]) -> None:

def f2() -> None:
A() # E: Cannot instantiate abstract class "A" with abstract attribute "method"
partial_cls = partial(A) # E: Cannot instantiate abstract class "A" with abstract attribute "method"
partial_cls = partial(A) # E: Cannot instantiate abstract class "A" with abstract attribute "method" \
# E: Argument 1 to "partial" has incompatible type "Type[A]"; expected "Callable[..., A]"
partial_cls() # E: Cannot instantiate abstract class "A" with abstract attribute "method"
[builtins fixtures/tuple.pyi]

Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-optional.test
Original file line number Diff line number Diff line change
Expand Up @@ -1343,3 +1343,19 @@ def f(x: object) -> None:
with C():
pass
[builtins fixtures/tuple.pyi]

[case testRefineAwayNoneCallbackProtocol]
# Regression test for issue encountered in https://github.com/python/mypy/pull/18347#issuecomment-2564062070
from __future__ import annotations
from typing import Protocol

class CP(Protocol):
def __call__(self, parameters: str) -> str: ...

class NotSet: ...

class Task:
def with_opt(self, trn: CP | type[NotSet] | None):
if trn is not NotSet:
reveal_type(trn) # N: Revealed type is "Union[__main__.CP, Type[__main__.NotSet], None]"
[builtins fixtures/tuple.pyi]
Loading