Multimethods

David Mertz, in this Charming Python column, makes multimethods sound hopelessly complicated like he always manages to do in his own inimitable way (sorry, David). After coming across the enlightening wikipedia article on multimethods though, I have since discovered that the concept is really quite simple to understand.

In a nutshell, Multimethods are nothing more than overloaded methods, but in a dynamic language context. Recall that in dynamic languages a function doesn’t usually care what type is being passed to it, so for example, the following Python function:

def addtwoitems(a,b):
  return a+b

can be fed strings, integers or any other object that support the + operator. Multimethods bestow more flexibility and control over this aspect of overloading. With them, you get to specify different function bodies depending on what the exact function signature is. So, again in Python using decorators:

@multimethod(int,int)
def addtwoitems(a,b):
  return a+b

@multimethod(str,str)
def addtwoitems(a,b):
  return a+" and "+b

etc…

This is basically nothing more than a cleaner way of expressing code as opposed to doing if-then type-checking clauses within a function. Armed with this introduction, hopefully you can go back to Mertz’s column and figure out the rest of what he is trying to say. 😛

Leave a Reply

Your email address will not be published. Required fields are marked *