Skip to main content
Python Software Foundation 20th Year Anniversary Fundraiser  Donate today!

Use self.super(*p, **kw) instead of super(cls, self).func(*p, **kw)

Project description

Automatically determine the correct super object and use it.

This module defines a mix-in class autosuper which has a single property - super.

The object returned by super can either be called or have attributes accessed. If it is called, a base class method with the same name as the current method will be called with the parameters passed. If an attribute is accessed a base class attribute will be returned.

Example of usage:

import autosuper

class A (autosuper.autosuper):

    def __init__ (self, a, b):
        self.super()
        print 'A.__init__'
        print a, b

    def test (self, a, b):
        print 'A.test'
        print b, a

class B (A):

    def __init__ (self):
        self.super(1, 2)
        print 'B.__init__'
        self.super.test(3, 4)

    def test (self, a, b):
        print 'B.test'
        print a, b

B()

produces:

A.__init__
1 2
B.__init__
A.test
4 3

We didn’t need to call self.super() in A.__init__ because the base class is object, but we can do so.

Note that B.test is never called - the call in B.__init__ to`self.super.test` ensures that only methods of classes higher in the MRO will be searched for test.

Note also that it is an error to call self.super.super - a TypeError will be raised.

Important: It is assumed that the code objects for each method are unique. Breakage is likely if methods share code objects (e.g. the code object for one method is assigned to another method).

Note: For performance reasons, this implementation modifies the bytecode of functions. To disable bytecode modification, set __super_modify_bytecode__ to False.

Project details


Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page