How to remember the order of arguments to super() in Python2
A handy mnemonic that eliminates the guesswork from picking the order of arguments for super()
by Danver Braganza on 2016-01-13
I don’t feel too bad admitting that despite more than a decade of writing
Python, I still get uneasy at times when I have to remember the order of
arguments to super()
in Python 2. If you write Object-Oriented Python 2 on a
semi-regular basis, you’re either struggling to remember the correct syntax
right now, or you have sucessfully memorized the order.
Of course Python 3 has already (mostly) fixed this problem with their updated super(), but some of us still have to work with Python 2, whether because we depend on legacy libraries, or because the business goals of our employers don’t justify putting the effort into upgrading.
In Python 2, is the order
class Cat(Animal):
def speak(self):
super(self, Cat).speak()
or is it
class Cat(Animal):
def speak(self):
super(Cat, self).speak()
?
Of course, if you pick the wrong option, Python will complain very loudly at you
when you call the broken speak()
in testing. You do test, don’t you?
TypeError: must be type, not Cat
# One of the examples above will raise this error. But which one?
# Keep reading to find out!
Confession time: Just over 10 years since starting with Python and I finally, FINALLY mastered the syntax for using the 'super()' built-in.
— Daniel Roy Greenfeld (@pydanny) January 13, 2016
Earlier today I saw this tweet by Daniel Greenfeld that reminded me about this, and I realized with a start that it was only a week ago I had unconsciously picked up the correct order. Of course, if I were to just say to you that the best way to memorize that was to go through the process of trial-and-error until you automatically pick up the order, this would be a very boring post.
Instead, I’m going to share a mnemonic that might help you take a shortcut to
remembering the order of super()
:
class Pirate(object):
def yarr(self):
print "Yarr"
class Me(Pirate):
def yarr(self):
"""How are yarr? I'm super, meself!"""
super(Me, self).yarr()
# Just remember, a pirate says meself, not selfme.
Hopefully you find this mnemonic useful the next time you’re writing a method
override and need to call super()
. If you have any feedback, please let me
know over at Hacker News.
Other articles you may like
- Misapplying LazyRecursiveDefaultDict A cautionary tale of how I misapplied the wrong software tool to a problem, and what I've learned from it.
- The Empty Case is not Special Instead of explicitly handling the empty case in functions, try this instead.
- Connect Four implemented in 3 lines of Python A tiny implementation of Connect 4 on the terminal, with explanation.