Skip to content

Instantly share code, notes, and snippets.

@gmarkall
Created April 25, 2011 12:15
Show Gist options
  • Save gmarkall/940427 to your computer and use it in GitHub Desktop.
Save gmarkall/940427 to your computer and use it in GitHub Desktop.
mm module (by Guido van Rossum)
registry = {}
class MultiMethod(object):
def __init__(self, name):
self._name = name
self._typemap = {}
def __call__(self, *args):
types = tuple(arg.__class__ for arg in args)
function = self._typemap.get(types)
if function is None:
raise TypeError("No match")
return function(*args)
def register(self, types, function):
if types in self._typemap:
raise TypeError("Duplicate registration")
self._typemap[types] = function
def multimethod(*types):
def register(function):
function = getattr(function, "__lastreg__", function)
name = function.__name__
mm = registry.get(name)
if mm is None:
mm = registry[name] = MultiMethod(name)
mm.register(types, function)
mm.__lastreg__ = function
return mm
return register
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment