Always call ancestor to avoid risks in Python code

Production RiskSoftware ResiliencyCode Reliability

Always call ancestor to avoid risks in Python code

This code insight counts one violation each time an __init__ method is not calling its ancestor.

In a class declared like:

class childClass (parentClass):
…def __init__(self):
……

The body of the __init__ function should contain the one of the following statements :

super( … ).__init__(…)
OR
one pattern parentClass.__init__(…) for each parent class. (there can be several parent class in case of multiple inheritance).

There is no violation if parentClass is the “object” class.

5362

Why you should care

If a base class has an __init__ method defined, its child classes should always call that method in their own __init__ implementations. Forgetting to call the base class’ __init__ method could leave instance members of it uninitialized. This can introduce bugs in a program if the derived class attempts to use any of the uninitialized instance members.

Business Impacts

 

Production Risk

CAST recommendations

References

https://www.quantifiedcode.com/knowledge-base/correctness/Call%20%60__init__%60%20method%20from%20base%20class/4MeaWnJD

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.

See featuresHow it works