Skip to content

Instantly share code, notes, and snippets.

@zachallaun
Created December 12, 2012 23:28
Show Gist options
  • Save zachallaun/4272664 to your computer and use it in GitHub Desktop.
Save zachallaun/4272664 to your computer and use it in GitHub Desktop.
Python multimethods with arbitrary dispatch
from multimethod import defmulti, defmethod
do_work = defmulti(type)
@defmethod(do_work, str)
def do_str_work(s):
return "a string"
@defmethod(do_work, int)
def do_int_work(i):
return "an int"
@defmethod(do_work, list)
def do_list_work(l):
return "a list"
@defmethod(do_work, tuple)
def do_tuple_work(t):
return "a tuple"
@defmethod(do_work, dict)
def do_dict_work(d):
return "a dict"
class DispatchError(Exception): pass
class defmulti(object):
def __init__(self, dispatch_fn):
self.dispatch_fn = dispatch_fn
self.implementations = {}
def __call__(self, *args, **kwargs):
dispatch = self.dispatch_fn(*args, **kwargs)
try:
impl = self.implementations[dispatch]
except KeyError:
raise DispatchError("no implementation found for dispatch value: "
+ str(dispatch))
return impl(*args, **kwargs)
def respond_to(self, dispatch, fn):
self.implementations[dispatch] = fn
def defmethod(mm, dispatch):
def register_method(fn):
mm.respond_to(dispatch, fn)
return fn
return register_method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment