Skip to content

Instantly share code, notes, and snippets.

@bcse
Created December 7, 2011 14:36
Show Gist options
  • Save bcse/1443027 to your computer and use it in GitHub Desktop.
Save bcse/1443027 to your computer and use it in GitHub Desktop.
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) # a generator expression!
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):
name = function.__name__
mm = registry.get(name)
if mm is None:
mm = registry[name] = MultiMethod(name)
mm.register(types, function)
return mm
return register
from mm import multimethod
@multimethod(int, int)
def foo(a, b):
print '2 integral numbers: %s' % str((a, b))
@multimethod(float, float)
def foo(a, b):
print '2 float numbers: %s' % str((a, b))
@multimethod(str, str)
def foo(a, b):
print '2 strings: %s' % str((a, b))
if __name__ == '__main__':
foo(1, 2)
foo(1.0, 2.0)
foo('a', 'b')
foo(1, 2.0) # TypeError: no match
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment