Missing call to superclass__del__ during object destruction¶
ID: py/missing-call-to-deleteKind: problemSecurity severity: Severity: errorPrecision: highTags: - quality - reliability - correctness - performanceQuery 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 finalizers are called during object finalization. However, the developer has responsibility for ensuring that objects are properly cleaned up, and that all superclass__del__ methods are called.
Classes with a__del__ method (a finalizer) typically hold some resource such as a file handle that needs to be cleaned up. If the__del__ method of a superclass is not called during object finalization, it is likely that resources may be leaked.
A call to the__del__ method of a superclass during object initialization may be unintentionally skipped:
If a subclass calls the
__del__method of the wrong class.If a call to the
__del__method of one its base classes is omitted.If a call to
super().__del__is used, but not all__del__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__del__ methods are properly called. Either each base class’s finalize method should be explicitly called, orsuper() calls should be consistently used throughout the inheritance hierarchy.
Example¶
In the following example, explicit calls to__del__ are used, butSportsCar erroneously callsVehicle.__del__. This is fixed inFixedSportsCar by callingCar.__del__.
classVehicle(object):def__del__(self):recycle(self.base_parts)classCar(Vehicle):def__del__(self):recycle(self.car_parts)Vehicle.__del__(self)#BAD: Car.__del__ is not called.classSportsCar(Car,Vehicle):def__del__(self):recycle(self.sports_car_parts)Vehicle.__del__(self)#GOOD: Car.__del__ is called correctly.classFixedSportsCar(Car,Vehicle):def__del__(self):recycle(self.sports_car_parts)Car.__del__(self)
References¶
Python Reference:del.
Python Standard Library:super.
Python Glossary:Method resolution order.