Skip to content

Commit fe8873f

Browse files
author
Juhi Chandalia
authored
Generates error when staticmethod and classmethod decorators are both used (#15118)
Fixes #14506
1 parent 9ce3470 commit fe8873f

File tree

3 files changed

+10
-0
lines changed

3 files changed

+10
-0
lines changed

mypy/message_registry.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@ def with_additional_msg(self, info: str) -> ErrorMessage:
268268
)
269269
CLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN: Final = 'Duplicate keyword pattern "{}"'
270270
CLASS_PATTERN_UNKNOWN_KEYWORD: Final = 'Class "{}" has no attribute "{}"'
271+
CLASS_PATTERN_CLASS_OR_STATIC_METHOD: Final = "Cannot have both classmethod and staticmethod"
271272
MULTIPLE_ASSIGNMENTS_IN_PATTERN: Final = 'Multiple assignments to name "{}" in pattern'
272273
CANNOT_MODIFY_MATCH_ARGS: Final = 'Cannot assign to "__match_args__"'
273274

mypy/semanal.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1548,6 +1548,8 @@ def visit_decorator(self, dec: Decorator) -> None:
15481548
self.fail("Only instance methods can be decorated with @property", dec)
15491549
if dec.func.abstract_status == IS_ABSTRACT and dec.func.is_final:
15501550
self.fail(f"Method {dec.func.name} is both abstract and final", dec)
1551+
if dec.func.is_static and dec.func.is_class:
1552+
self.fail(message_registry.CLASS_PATTERN_CLASS_OR_STATIC_METHOD, dec)
15511553

15521554
def check_decorated_function_is_method(self, decorator: str, context: Context) -> None:
15531555
if not self.type or self.is_func_scope():

test-data/unit/check-classes.test

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1395,6 +1395,13 @@ main:8: note: def f(cls) -> None
13951395
main:8: note: Subclass:
13961396
main:8: note: def f(self) -> None
13971397

1398+
[case testClassMethodAndStaticMethod]
1399+
class C:
1400+
@classmethod # E: Cannot have both classmethod and staticmethod
1401+
@staticmethod
1402+
def foo(cls) -> None: pass
1403+
[builtins fixtures/classmethod.pyi]
1404+
13981405
-- Properties
13991406
-- ----------
14001407

0 commit comments

Comments
 (0)