Missing call to superclass__init__ during object initialization¶
ID: py/missing-call-to-initKind: problemSecurity severity: Severity: errorPrecision: highTags: - quality - reliability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
Python, unlike some other object-oriented languages such as Java, allows the developer complete freedom in when and how superclass initializers are called during object initialization. However, the developer has responsibility for ensuring that objects are properly initialized, and that all superclass__init__ methods are called.
If the__init__ method of a superclass is not called during object initialization, this can lead to errors due to the object not being fully initialized, such as having missing attributes.
A call to the__init__ method of a superclass during object initialization may be unintentionally skipped:
If a subclass calls the
__init__method of the wrong class.If a call to the
__init__method of one its base classes is omitted.If a call to
super().__init__is used, but not all__init__methods in the Method Resolution Order (MRO) chain themselves callsuper(). This in particular arises more often in cases of multiple inheritance.
Recommendation¶
Ensure that all superclass__init__ methods are properly called. Either each base class’s initialize method should be explicitly called, orsuper() calls should be consistently used throughout the inheritance hierarchy.
Example¶
In the following example, explicit calls to__init__ are used, butSportsCar erroneously callsVehicle.__init__. This is fixed inFixedSportsCar by callingCar.__init__.
classVehicle(object):def__init__(self):self.mobile=TrueclassCar(Vehicle):def__init__(self):Vehicle.__init__(self)self.car_init()# BAD: Car.__init__ is not called.classSportsCar(Car,Vehicle):def__init__(self):Vehicle.__init__(self)self.sports_car_init()# GOOD: Car.__init__ is called correctly.classFixedSportsCar(Car,Vehicle):def__init__(self):Car.__init__(self)self.sports_car_init()
References¶
Python Reference:init.
Python Standard Library:super.
Python Glossary:Method resolution order.