Skip to content
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
5 changes: 5 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@
)
from mypy.typeops import function_type, get_type_vars, try_getting_str_literals_from_type
from mypy.types import (
ANNOTATED_TYPE_NAMES,
ASSERT_TYPE_NAMES,
DATACLASS_TRANSFORM_NAMES,
DEPRECATED_TYPE_NAMES,
Expand Down Expand Up @@ -1190,11 +1191,15 @@ def is_expected_self_type(self, typ: Type, is_classmethod: bool) -> bool:
sym = self.lookup_qualified(typ.name, typ, suppress_errors=True)
if sym is not None and sym.fullname in TYPE_NAMES and typ.args:
return self.is_expected_self_type(typ.args[0], is_classmethod=False)
if sym is not None and sym.fullname in ANNOTATED_TYPE_NAMES and typ.args:
return self.is_expected_self_type(typ.args[0], is_classmethod=True)
return False
if isinstance(typ, TypeVarType):
return typ == self.type.self_type
if isinstance(typ, UnboundType):
sym = self.lookup_qualified(typ.name, typ, suppress_errors=True)
if sym is not None and sym.fullname in ANNOTATED_TYPE_NAMES and typ.args:
return self.is_expected_self_type(typ.args[0], is_classmethod=False)
return sym is not None and sym.fullname in SELF_TYPE_NAMES
return False

Expand Down
18 changes: 18 additions & 0 deletions test-data/unit/check-selftype.test
Original file line number Diff line number Diff line change
Expand Up @@ -1549,6 +1549,24 @@ reveal_type(D.meth()) # N: Revealed type is "__main__.D"
reveal_type(D.bad()) # N: Revealed type is "Never"
[builtins fixtures/classmethod.pyi]

[case testTypingSelfAnnotatedType]
# See: https://github.com/python/mypy/issues/21917

from typing import Self
from typing_extensions import Annotated

class C:
def foo(self: Annotated[Self, "some_metadata"], x: int) -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could you add a check for a classmethod too? I think you missed that case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I missed that, thanks.

...

@classmethod
def bar(self: Annotated[type[Self], "some_metadata"], x: int) -> None:
...

reveal_type(C.foo) # N: Revealed type is "def [Self <: __main__.C] (self: Self`2, x: builtins.int)"
reveal_type(C.bar) # N: Revealed type is "def (x: builtins.int)"
[builtins fixtures/tuple.pyi]

[case testTypingSelfOverload]
from typing import Self, overload, Union

Expand Down
Loading