Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Python 3 super() in Python 2.5.6?

Can I use clean Python 3 super() syntax in Python 2.5.6?
Maybe with some kind of __future__ import?

like image 441
Dan Abramov Avatar asked Oct 10 '11 21:10

Dan Abramov


People also ask

Is super () necessary Python?

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 ).

What is super () python?

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.

How do I know if a script is Python 2 or 3?

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.

What is super with arguments in python?

“[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.


2 Answers

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
like image 74
posita Avatar answered Sep 23 '22 17:09

posita


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.

like image 32
donkopotamus Avatar answered Sep 21 '22 17:09

donkopotamus