Skip to content
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

Handle type[...] same as typing.Type[...] in classmethod 1st arg #15297

Merged
merged 5 commits into from
Jul 4, 2023
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
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