From 85ba5745afcc646c1728dbb690bfb196537abe04 Mon Sep 17 00:00:00 2001 From: Erik Kemperman Date: Tue, 4 Jul 2023 20:17:31 +0200 Subject: [PATCH] Handle type same as typing.Type in classmethod 1st arg (#15297) --- mypy/semanal.py | 16 ++++++++++++- test-data/unit/check-selftype.test | 36 ++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index 75d41b344698..1f15691ae205 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -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): diff --git a/test-data/unit/check-selftype.test b/test-data/unit/check-selftype.test index 96d5b2306427..4155e3343851 100644 --- a/test-data/unit/check-selftype.test +++ b/test-data/unit/check-selftype.test @@ -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" @@ -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