Sathish Sathish - 1 year ago 73
Python Question

When should I use the keyword super in Base class in python?

I am trying to understand this piece of code in python. From my understanding,

is used to call a base class function from derived class when you don't want to explicitly write the name of the base class. But as mentioned below, what does it mean if the base class itself uses
to call some function?

class ReviewViewMixin(object):
def dispatch(self, request, *args, **kwargs):
# some code
return super(ReviewViewMixin, self).dispatch(request, *args, **kwargs)

class ReviewCreateView(ReviewViewMixin, CreateView):
# some code
def dispatch(self, request, *args, **kwargs):
super(ReviewCreateView, self).dispatch(request, *args, **kwargs)

I tried creating few sample classes like above but I get the expected "no such parameter" exception.

Answer Source

You'll notice that your class ReviewCreateView has two (direct) base classes. super is necessary to make sure that the dispatch method gets called on both of those base classes.

Whenever a class is created, python looks at the inheritance tree and flattens it which creates something called the "Method Resolution Order" (MRO). In this case, your MRO is probably1:

ReviewCreateView, ReviewViewMixin, CreateView, ..., object

What super does is it inspects the current MRO and it calls the method on the next class in the MRO. Your call stack will look like:

ReviewCreateView.dispatch (super) -> ReviewViewMixin.dispatch (super) -> CreateView.dispatch

Now note that if ReviewViewMixin didn't have a super in there, the call stack would have ended with it. However, since it has a super and the next class in the MRO is CreateView, CreateView's dispatch method will also get called.

Super can be tricky to really wrap your head around -- I'd suggest reading the "super is Super" article by Raymond Hettinger for some ideas and best-practices.

1You can inspect the MRO by using inspect.getmro(ReviewCreateView) or simply looking at ReviewCreateView.__mro__

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download