Search code examples
pythonpython-3.xsubclasssuper

When to call Python's super().__init__()?


(I am unable to find a reference anywhere on this matter after some Googling.)

The scenario can be clearly demonstrated with this short code sample:

class X:
    def __init__(self, stuff):
        self.__stuff = stuff

class Y(X):
    def __init__(self, stuff):
        # Is it safe to execute statements before calling super.__init__()?
        new_stuff = self.call_another_method(stuff)
        super(Y, self).__init__(new_stuff)

Using CPython 3.x, the above code sample works -- assuming call_another_method() exists. It this coding style generally safe, but frowned upon or considered unPythonic? I am unable to find advice on this matter.

Why do I care?

My background comes from more traditional object oriented programming languages such as C++, C#, and Java where "super" must be called strictly as the first statement in a subclass constructor -- ignoring the zero-argument, implicit case.

If it matters, I am a young Pythoneer: 3+, please.


Solution

  • Yes, it is perfectly safe to call other things before super(). Python doesn't set an order, and there are plenty of use-cases for this.

    Note that super().__init__() call is just another expression in Python, it is not a syntax construct. You can use super() outside methods too, for example, provided you pass in the right arguments.

    In your case, you can omit the type and instance arguments, Python 3 will retrieve these for you when super() is called without arguments, because you are using it in a function defined inside a class:

    class Y(X):
        def __init__(self, stuff):
            new_stuff = self.call_another_method(stuff)
            # super(Y, self) is implicit here:
            super().__init__(new_stuff)