Skip to main content

Python's super() Abused as a Hook

There has been some recent-ish discussion on the python-dev mailing list about "fixing" the super built-in, which is used to access attributes of an object with lookup rules on the superclass of a given class. This is used for different things and in different ways, but the most common usage seems to be as follows:

class Foo(Bar):
def action(self):
super(Foo, self).action()
self.actionCalledOnFooInstance = True

This causes a call to Foo().action() to call the action method of the next class in the Method Resolution Order. Now, Bar.action might exist, or maybe Bar inherits from Baz and Baz.action() will be called. The point is, you don't have to know. The typical pattern here is the that we are looking for the superclass of the same class we are within (Foo) and call the same method we're already in (action), which is a repetition some people want to fix.

I propose that super() is not broken at all, or even failing, but simply that we are misusing it where anothing idiom may be more appropriate. The more appropriate idiom might be hooks. Sometimes our function using super() should actually be calling a hook and other times it should be the hook. In the example above, we want something to happen after the regular action() method is called, so we redefine the entire action() method to call the original and then execute our one little line. We require all the overhead and issues with super() largely for varients of this common use case. Instead, consider if we wrote the following:

class Foo(Bar):
def hook_after_action(self):
self.actionCalledOnFooInstance = True

Do you see how much simpler that is? The requirement here is that either super(Foo, self).action would call hook_after_action if it exists (or there could be a default no-op version) or some mechanism outside of the action() method might handle it, perhaps wrapping it up on request or at definition. Maybe a standard hook format could even be a candidate for brining into the language.

Hooks are very valuable concepts that are not used enough. We can save ourselves a lot of trouble by using them. There is a lot more I could say about them, but this post was mostly about their relation to the many use cases of super.

PS - Some of this can be known to relate to the concept called "Aspect-Oriented Programm" which has very little weight in the Python world, because here its so easy to do that it doesn't deserve a name and is reduced to simply wrapping functions or having hooks.

Comments

fumanchu said…
Within reason, yes. Classes which have a few, standard extension points are better written as hooks. But there are classes (such as adapters) where potentially every method needs to be extended. Adding a pre hook and a post hook to every method would be silly, polluting the namespace unnecessarily. The choice of when to add a hook method shouldn't be left to a whim.

One option is to isolate the hooks into a separate Hookset object, so that the space of hook names is at least isolated from the class namespace.
Ludvig said…
"...the super built-in, which is used to access attributes of an object with lookup rules on the superclass of a given class."

What you're saying here isn't entirely correct and much of the Python community is wrong here.

To lay it quick, what super() actually does is that it returns a proxy object of the attribute that would've been returned if the current function hadn't been called. The difference here is when it comes to MRO - multiple inheritance.

I suggest reading http://fuhm.net/super-harmful/ - it explains what I mean better than I can do quickly here.
Anonymous said…
This is wrong in a couple of ways. First, you do need to know whether baz.action is being called or bar.action is being called. Things are going to be screwed up, and you're going to be debugging, and it's going to be important that you know exactly which routine was called when.

Secondly, it's going to be the case that you want both of baz.action and bar.action to be called. The hook approach won't work. As soon as you declare your hook, it overrides the hook in the superclass that you wanted to have called. So, your hook needs to call super(foo, self).hook().

Popular posts from this blog

Why I Switched From Git to Microsoft OneDrive

I made the unexpected move with a string of recent projects to drop Git to sync between my different computers in favor of OneDrive, the file sync offering from Microsoft. Its like Dropbox, but "enterprise."

Feeling a little ashamed at what I previously would have scoffed at should I hear of it from another developer, I felt a little write up of the why and the experience could be a good idea. Now, I should emphasize that I'm not dropping Git for all my projects, just specific kinds of projects. I've been making this change in habit for projects that are just for me, not shared with anyone else. It has been especially helpful in projects I work on sporadically. More on why a little later.

So, what drove me away from Git, exactly?

On the smallest projects, like game jam hacks, I just wanted to code. I didn't want to think about revisions and commit messages. I didn't need branching or merges. I didn't even need to rollback to another version, ever. I just …

Respect and Code Reviews

Code Reviews in a development team only function best, or possible at all, when everyone approaches them with respect. That’s something I’ve usually taken for granted because I’ve had the opportunity to work with amazing developers who shine not just in their technical skills but in their interpersonal skills on a team. That isn’t always the case, so I’m going to put into words something that often exists just in assumptions.
You have to respect your code. This is first only because the nature and intent of code reviews are to safeguard the quality of your code, so even having code reviews demonstrates a baseline of respect for that code. But, maybe not everyone on the team has the same level of respect or entered a team with existing review traditions that they aren’t acquainted with.
There can be culture shock when you enter a team that’s really heavy on code reviews, but also if you enter a team or interact with a colleague who doesn’t share that level of respect for the process or…

CARDIAC: The Cardboard Computer

I am just so excited about this.


CARDIAC. The Cardboard Computer. How cool is that? This piece of history is amazing and better than that: it is extremely accessible. This fantastic design was built in 1969 by David Hagelbarger at Bell Labs to explain what computers were to those who would otherwise have no exposure to them. Miraculously, the CARDIAC (CARDboard Interactive Aid to Computation) was able to actually function as a slow and rudimentary computer. 
One of the most fascinating aspects of this gem is that at the time of its publication the scope it was able to demonstrate was actually useful in explaining what a computer was. Could you imagine trying to explain computers today with anything close to the CARDIAC?

It had 100 memory locations and only ten instructions. The memory held signed 3-digit numbers (-999 through 999) and instructions could be encoded such that the first digit was the instruction and the second two digits were the address of memory to operate on. The only re…