Skip to content

Correctly handle cls in protocol classmethod #11119

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

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
3 changes: 2 additions & 1 deletion mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,8 @@ def find_node_type(node: Union[Var, FuncBase], itype: Instance, subtype: Type) -
and node.is_initialized_in_class
and not node.is_staticmethod)):
assert isinstance(typ, FunctionLike)
signature = bind_self(typ, subtype)
signature = bind_self(typ, subtype,
is_classmethod=isinstance(node, Var) and node.is_classmethod)
if node.is_property:
assert isinstance(signature, CallableType)
typ = signature.ret_type
Expand Down
31 changes: 31 additions & 0 deletions test-data/unit/check-selftype.test
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,37 @@ class Bad(metaclass=Meta):
Good.do_x()
Bad.do_x() # E: Invalid self argument "Type[Bad]" to attribute function "do_x" with type "Callable[[Type[T]], T]"

[case testSelfTypeProtocolClassmethodMatch]
from typing import Type, TypeVar, Protocol

T = TypeVar('T')

class HasDoX(Protocol):
@classmethod
Copy link
Member

Choose a reason for hiding this comment

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

What about @staticmethod? Does it fall into the same problem?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

staticmethod doesn't have this problem, because there's no self/cls to bind

def do_x(cls: Type[T]) -> T:
...

class Good:
@classmethod
def do_x(cls) -> 'Good':
...

class Bad:
@classmethod
def do_x(cls) -> Good:
...

good: HasDoX = Good()
bad: HasDoX = Bad()
[builtins fixtures/classmethod.pyi]
[out]
main:21: error: Incompatible types in assignment (expression has type "Bad", variable has type "HasDoX")
main:21: note: Following member(s) of "Bad" have conflicts:
main:21: note: Expected:
main:21: note: def do_x(cls) -> Bad
main:21: note: Got:
main:21: note: def do_x(cls) -> Good

[case testSelfTypeNotSelfType]
# Friendlier error messages for common mistakes. See #2950
class A:
Expand Down