Skip to content

Commit 85ba574

Browse files
Handle type same as typing.Type in classmethod 1st arg (#15297)
1 parent 913477e commit 85ba574

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

mypy/semanal.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1008,7 +1008,21 @@ def is_expected_self_type(self, typ: Type, is_classmethod: bool) -> bool:
10081008
return self.is_expected_self_type(typ.item, is_classmethod=False)
10091009
if isinstance(typ, UnboundType):
10101010
sym = self.lookup_qualified(typ.name, typ, suppress_errors=True)
1011-
if sym is not None and sym.fullname == "typing.Type" and typ.args:
1011+
if (
1012+
sym is not None
1013+
and (
1014+
sym.fullname == "typing.Type"
1015+
or (
1016+
sym.fullname == "builtins.type"
1017+
and (
1018+
self.is_stub_file
1019+
or self.is_future_flag_set("annotations")
1020+
or self.options.python_version >= (3, 9)
1021+
)
1022+
)
1023+
)
1024+
and typ.args
1025+
):
10121026
return self.is_expected_self_type(typ.args[0], is_classmethod=False)
10131027
return False
10141028
if isinstance(typ, TypeVarType):

test-data/unit/check-selftype.test

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1665,6 +1665,23 @@ class C:
16651665
return cls()
16661666
[builtins fixtures/classmethod.pyi]
16671667

1668+
[case testTypingSelfRedundantAllowed_pep585]
1669+
# flags: --python-version 3.9
1670+
from typing import Self
1671+
1672+
class C:
1673+
def f(self: Self) -> Self:
1674+
d: Defer
1675+
class Defer: ...
1676+
return self
1677+
1678+
@classmethod
1679+
def g(cls: type[Self]) -> Self:
1680+
d: DeferAgain
1681+
class DeferAgain: ...
1682+
return cls()
1683+
[builtins fixtures/classmethod.pyi]
1684+
16681685
[case testTypingSelfRedundantWarning]
16691686
# mypy: enable-error-code="redundant-self"
16701687

@@ -1683,6 +1700,25 @@ class C:
16831700
return cls()
16841701
[builtins fixtures/classmethod.pyi]
16851702

1703+
[case testTypingSelfRedundantWarning_pep585]
1704+
# flags: --python-version 3.9
1705+
# mypy: enable-error-code="redundant-self"
1706+
1707+
from typing import Self
1708+
1709+
class C:
1710+
def copy(self: Self) -> Self: # E: Redundant "Self" annotation for the first method argument
1711+
d: Defer
1712+
class Defer: ...
1713+
return self
1714+
1715+
@classmethod
1716+
def g(cls: type[Self]) -> Self: # E: Redundant "Self" annotation for the first method argument
1717+
d: DeferAgain
1718+
class DeferAgain: ...
1719+
return cls()
1720+
[builtins fixtures/classmethod.pyi]
1721+
16861722
[case testTypingSelfAssertType]
16871723
from typing import Self, assert_type
16881724

0 commit comments

Comments
 (0)