Skip to content

Bind self-types in checkmember for decorated classmethods #19025

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 2 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
8 changes: 7 additions & 1 deletion mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -1203,9 +1203,15 @@ def analyze_class_attribute_access(
t = get_proper_type(t)
if isinstance(t, FunctionLike) and is_classmethod:
t = check_self_arg(t, mx.self_type, False, mx.context, name, mx.msg)
result = add_class_tvars(
t = add_class_tvars(
t, isuper, is_classmethod, is_staticmethod, mx.self_type, original_vars=original_vars
)
if is_decorated and not is_staticmethod:
t = expand_self_type_if_needed(
t, mx, cast(Decorator, node.node).var, itype, is_class=is_classmethod
)

result = t
# __set__ is not called on class objects.
if not mx.is_lvalue:
result = analyze_descriptor_access(result, mx)
Expand Down
41 changes: 41 additions & 0 deletions test-data/unit/check-selftype.test
Original file line number Diff line number Diff line change
Expand Up @@ -2221,3 +2221,44 @@ class B:
class C(A, B): # OK: both methods take Self
pass
[builtins fixtures/tuple.pyi]

[case testSelfInFuncDecoratedClassmethod]
from collections.abc import Callable
from typing import Self, TypeVar

T = TypeVar("T")

def debug(make: Callable[[type[T]], T]) -> Callable[[type[T]], T]:
return make

class Foo:
@classmethod
@debug
def make(cls) -> Self:
return cls()

class Bar(Foo): ...

reveal_type(Foo.make()) # N: Revealed type is "__main__.Foo"
reveal_type(Foo().make()) # N: Revealed type is "__main__.Foo"
reveal_type(Bar.make()) # N: Revealed type is "__main__.Bar"
reveal_type(Bar().make()) # N: Revealed type is "__main__.Bar"
[builtins fixtures/tuple.pyi]

[case testSelfInClassDecoratedClassmethod]
from typing import Callable, Generic, TypeVar, Self

T = TypeVar("T")

class W(Generic[T]):
def __init__(self, fn: Callable[..., T]) -> None: ...
def __call__(self) -> T: ...

class Check:
@W
def foo(self) -> Self:
...

reveal_type(Check.foo()) # N: Revealed type is "def () -> __main__.Check"
reveal_type(Check().foo()) # N: Revealed type is "__main__.Check"
[builtins fixtures/tuple.pyi]