Same Method And Attribute Name

ID

python.same_method_field_names

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Python

Tags

reliability, suspicious-construct

Description

Reports classes where a method name and an instance attribute share the same identifier (or differ only in case). They share a single namespace on the instance: assigning self.value = 1 in init silently overwrites def value(self): …​, so any later call to obj.value() raises TypeError.

class Bad:
    def value(self):
        return self._value

    def __init__(self):
        self.value = 0           # FLAW — shadows the method

class Good:
    def value(self):
        return self._value

    def __init__(self):
        self._value = 0          # OK

Rationale

The bug appears only when something tries to invoke the method, often far from the assignment. Static detection finds the conflict at the class definition.

The rule also flags case-only collisions (def Value(self) plus self.value = …​) because Python attribute lookup is case-sensitive — the two names look related but resolve to different slots, almost always confusing readers.

Remediation

Rename the attribute (the convention is a single underscore prefix for the backing field) or rename the method.