Subclass init Calls Parent
ID |
python.init_call_parent |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Python |
Tags |
reliability, suspicious-construct |
Description
Reports init methods inside a subclass that do not invoke the parent’s constructor. Without super().init(…), any state the parent class needs to initialise on the instance never runs, and the resulting object is partially constructed in ways the parent’s other methods rely on.
class Bad(Parent):
def __init__(self): # FLAW — Parent.__init__ never runs
self.x = 1
class Good(Parent):
def __init__(self):
super().__init__()
self.x = 1
Rationale
Skipping the parent constructor is sometimes intentional (the parent does heavy work the subclass does not need), but the silent failures it introduces — methods of the parent that rely on attributes set in init raising AttributeError later — are usually worse than the few microseconds saved.
The rule fires only when the class extends from at least one named super-type other than object; classes with no explicit base are out of scope.
Remediation
Add the super().init(…) call at the start of the subclass init. Forward whatever arguments the parent expects:
class Good(Parent):
def __init__(self, x):
super().__init__(x)
self.cache = {}
If the parent constructor really must be skipped, document the reason in a comment so future readers do not "fix" it back.