First Argument Reassigned

ID

python.first_arg_reassigned

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Python

Tags

reliability, suspicious-construct

Description

Reports methods that reassign their first implicit argument — self for instance methods or cls for @classmethod. Reassigning self does not change the actual instance; it only rebinds the local name. The rest of the method then operates on a different object than the caller’s instance, which is almost certainly not the intent.

class Bad:
    def reset(self):
        self = OtherType()       # FLAW — local rebind, no effect on caller

class BadCls:
    @classmethod
    def make(cls):
        cls = SomeOther           # FLAW — same problem
        return cls()

Rationale

Most occurrences of self = …​ are refactoring mistakes — the developer meant to mutate an attribute (self.x = …​) or to return a new instance (which is what new is for). Catching the rebind statically removes a class of "why is this method doing nothing" debugging.

Remediation

If the intent is to mutate an attribute, use self.attr = …​. If the intent is to construct a new instance, return it from a classmethod or factory function rather than reassigning self.