cls as First Argument

ID

python.cls_first_argument

Severity

low

Remediation Complexity

trivial

Remediation Risk

medium

Remediation Effort

low

Resource

Naming Convention

Language

Python

Tags

code-style, naming

Description

Reports @classmethod methods whose first parameter is not named cls. Python passes the class itself as the first argument, and PEP 8 establishes the convention cls. The rule fires only on methods decorated with @classmethod; instance methods are covered by python.self_first_argument.

class Bad:
    @classmethod
    def make(klass):                # FLAW
        return klass()

class Good:
    @classmethod
    def make(cls):
        return cls()

Rationale

Same idea as self for instance methods: convention is the whole point. A name that breaks the convention demands the reader’s attention every time, even when nothing else is wrong. cls is also what every IDE / linter / docstring template assumes.

For metaclass methods the convention is mcs (or cls); the rule treats both as acceptable.

Remediation

Rename the parameter to cls. The rest of the method body needs the same rename, which any IDE handles automatically.