In python, super() is always called first in a method. Are there situations where it should be called later?

TomOnTime picture TomOnTime · Apr 12, 2011 · Viewed 7.3k times · Source

Are there situations where you want to do some processing before you call super()?

This is a contrived example. Are there better examples? Is this considered pythonic?

class Base(object):
    def __init__(self, name):
        print "Base %s created" % name
        self._name = name

class UpperBase(A):
    """ Similar to base but the name is in uppercase. """
    def __init__(self, name):
        name = name.upper() 
        super(UpperBase, self).__init__(name)

Answer

Gabi Purcaru picture Gabi Purcaru · Apr 12, 2011

Sometimes you need to validate the arguments before calling super():

class UpperBase(Base):
    def __init__(self, name):
        if not name_valid(name):
            raise ValueError()
        super(UpperBase, self).__init__(name)

I don't see why this wouldn't be pythonic, because it's the easiest way to do it and it's straightforward. Also, read @JHSaunders' comment, he makes a good point.