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

Question:

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)
Asked By: TomOnTime

||

Answers:

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.

Answered By: Gabi Purcaru
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.