Can I use clean Python 3 super()
syntax in Python 2.5.6?
Maybe with some kind of __future__
import?
In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
If you want to determine whether Python2 or Python3 is running, you can check the major version with this sys. version_info. major . 2 means Python2, and 3 means Python3.
“[Super is used to] return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
I realize this question is old, and the selected answer may have been correct at the time, but it's no longer complete. You still can't use super()
in 2.5.6, but python-future
provides a back-ported implementation for 2.6+:
Install python-future
with:
% pip install future
The following shows the redefinition of super
under builtins
:
% python
...
>>> import sys
>>> sys.version_info[:3]
(2, 7, 9)
>>>
>>> super
<type 'super'>
>>>
>>> from builtins import *
>>> super
<function newsuper at 0x000000010b4832e0>
>>> super.__module__
'future.builtins.newsuper'
It can be used as follows:
from builtins import super
class Foo(object):
def f(self):
print('foo')
class Bar(Foo):
def f(self):
super().f() # <- whoomp, there it is
print('bar')
b = Bar()
b.f()
which outputs
foo
bar
If you use pylint
, you can disable legacy warnings with the comment:
# pylint: disable=missing-super-argument
You cannot use a bare super()
call that contains no type/class. Nor can you implement a replacement for it that will work. Python 3.x contains special support to enable bare super()
calls (it places a __class__
cell variable in all functions defined within a class - see PEP 3135
Update
As of Python 2.6+, bare super()
calls can be used via the future
Python package. See posita's answer for an explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With