Skip to content

Commit

Permalink
Handle type same as typing.Type in classmethod 1st arg (#15297)
Browse files Browse the repository at this point in the history
  • Loading branch information
erikkemperman authored Jul 4, 2023
1 parent 913477e commit 85ba574
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
16 changes: 15 additions & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1008,7 +1008,21 @@ def is_expected_self_type(self, typ: Type, is_classmethod: bool) -> bool:
return self.is_expected_self_type(typ.item, is_classmethod=False)
if isinstance(typ, UnboundType):
sym = self.lookup_qualified(typ.name, typ, suppress_errors=True)
if sym is not None and sym.fullname == "typing.Type" and typ.args:
if (
sym is not None
and (
sym.fullname == "typing.Type"
or (
sym.fullname == "builtins.type"
and (
self.is_stub_file
or self.is_future_flag_set("annotations")
or self.options.python_version >= (3, 9)
)
)
)
and typ.args
):
return self.is_expected_self_type(typ.args[0], is_classmethod=False)
return False
if isinstance(typ, TypeVarType):
Expand Down
36 changes: 36 additions & 0 deletions test-data/unit/check-selftype.test
Original file line number Diff line number Diff line change
Expand Up @@ -1665,6 +1665,23 @@ class C:
return cls()
[builtins fixtures/classmethod.pyi]

[case testTypingSelfRedundantAllowed_pep585]
# flags: --python-version 3.9
from typing import Self

class C:
def f(self: Self) -> Self:
d: Defer
class Defer: ...
return self

@classmethod
def g(cls: type[Self]) -> Self:
d: DeferAgain
class DeferAgain: ...
return cls()
[builtins fixtures/classmethod.pyi]

[case testTypingSelfRedundantWarning]
# mypy: enable-error-code="redundant-self"

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

[case testTypingSelfRedundantWarning_pep585]
# flags: --python-version 3.9
# mypy: enable-error-code="redundant-self"

from typing import Self

class C:
def copy(self: Self) -> Self: # E: Redundant "Self" annotation for the first method argument
d: Defer
class Defer: ...
return self

@classmethod
def g(cls: type[Self]) -> Self: # E: Redundant "Self" annotation for the first method argument
d: DeferAgain
class DeferAgain: ...
return cls()
[builtins fixtures/classmethod.pyi]

[case testTypingSelfAssertType]
from typing import Self, assert_type

Expand Down

0 comments on commit 85ba574

Please sign in to comment.