Search code examples
pythonmultiple-inheritance

Why do I have to specify my own class when using super(), and is there a way to get around it?


When using Python's super() to do method chaining, you have to explicitly specify your own class, for example:

class MyDecorator(Decorator):
    def decorate(self):
        super(MyDecorator, self).decorate()

I have to specify the name of my class MyDecorator as an argument to super(). This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?


Solution

  • The BDFL agrees. In Python 3.0, support for super() with no arguments was added:

    PEP 3135: New super(). You can now invoke super() without arguments and (assuming this is in a regular instance method defined inside a class statement) the right class and instance will automatically be chosen. With arguments, the behavior of super() is unchanged.

    Also see Pep 367 - New Super for Python 2.6.