Static Method No Self

ID

python.static_method_no_self

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Python

Tags

reliability, suspicious-construct

Description

Reports @staticmethod methods whose first parameter is named self or cls. A static method does not receive an implicit instance or class, so self / cls in the signature is misleading at best (every reader has to double-check the decorator is really there) and a latent bug at worst (the method may have been an instance method that someone bolted @staticmethod onto without adjusting the signature).

class Bad:
    @staticmethod
    def helper(self, x):       # FLAW
        return x

class Good:
    @staticmethod
    def helper(x):
        return x

Rationale

When the first argument of a static method is self, the call site Cls.helper(value) passes value as self, which silently changes its meaning. The body then references self thinking it is the instance, but it is whatever the caller passed first. The bug is invisible until the method is invoked.

Remediation

Drop the self / cls parameter, or remove the @staticmethod decorator if the method really does need an instance.