‘super’ in old style class¶
ID: py/super-in-old-styleKind: problemSecurity severity: Severity: errorPrecision: very-highTags: - portability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
The ability to access inherited methods that have been overridden in a class usingsuper() is supported only by new-style classes. When you use thesuper() function in an old-style class it fails.
Recommendation¶
If you want to access inherited methods using thesuper() built-in, then ensure that the class is a new-style class. You can convert an old-style class to a new-style class by inheriting fromobject. Alternatively, you can call the__init__ method of the superclass directly from an old-style class using:BaseClass.__init__(...).
Example¶
In the following example,PythonModule is an old-style class as it inherits from another old-style class. If the_ModuleIteratorHelper class cannot be converted into a new-style class, then the call tosuper() must be replaced. ThePythonModule2 class demonstrates the correct way to call a superclass from an old-style class.
classPythonModule(_ModuleIteratorHelper):# '_ModuleIteratorHelper' and 'PythonModule' are old-style classes# class definitions ....defwalkModules(self,importPackages=False):ifimportPackagesandself.isPackage():self.load()returnsuper(PythonModule,self).walkModules(importPackages=importPackages)# super() will failclassPythonModule2(_ModuleIteratorHelper):# call to super replaced with direct call to class# class definitions ....defwalkModules(self,importPackages=False):ifimportPackagesandself.isPackage():self.load()return_ModuleIteratorHelper.__init__(PythonModule,self).walkModules(importPackages=importPackages)
References¶
Python Glossary:New-style class.
Python Language Reference:New-style and classic classes.
Python Standard Library:super.