This rule raises an issue when the same class field is unconditionally assigned multiple times within a class body.
Why is this an issue?
When a class field is defined multiple times in the same class body, only the last assignment takes effect. All previous assignments are dead code
that serve no purpose.
This pattern typically occurs due to:
- copy-paste errors: duplicating code blocks without updating field names
- refactoring mistakes: forgetting to remove old assignments when updating values
- merge conflicts: incorrectly resolving version control conflicts
- misunderstanding: confusion about how class attributes work
What is the potential impact?
- confusion: developers may not immediately realize which value is actually used
- maintenance burden: dead code must be read, understood, and maintained even though it has no effect
- hidden bugs: the duplicate definition might indicate that two different fields were intended, suggesting a naming error that
could lead to incorrect behavior
How to fix it
Remove all but the last assignment to the class field. Keep only the final value that should be used.
Code examples
Noncompliant code example
class MyClass:
x = 1
y = 2
x = 3 # Noncompliant: "x" is defined twice
Compliant solution
class MyClass:
x = 3
y = 2
Resources
Documentation
Related rules
- {rule:python:S4143} - Collection content should not be replaced unconditionally
- {rule:python:S1534} - Member names should not be duplicated within a class or object literal