Skip to content

Instantly share code, notes, and snippets.

@inlinestyle
Last active December 12, 2015 03:58
Show Gist options
  • Save inlinestyle/4710716 to your computer and use it in GitHub Desktop.
Save inlinestyle/4710716 to your computer and use it in GitHub Desktop.
from collections import defaultdict
import functools
class multimethod(object):
"""
multimethod.register('function', dispatcher)
@multimethod.register('function')
def dispatcher(): pass
@multimethod(dispatch_value)
def function(*args, **kwargs): pass
"""
_dispatchers = {}
_functions = defaultdict(dict)
def __init__(self, dispatch_value):
self._dispatch_value = dispatch_value
def __call__(self, function):
self._functions[function.__name__][self._dispatch_value] = function
dispatcher = self._dispatchers[function.__name__]
def proxy(*args, **kwargs):
return self._functions[function.__name__][dispatcher(*args, **kwargs)](*args, **kwargs)
return proxy
@classmethod
def register(cls, name, dispatcher=None):
if dispatcher is not None:
cls._dispatchers[name] = dispatcher
else:
return functools.partial(cls.register, name)
#Example
@multimethod.register('add_event')
def dispatch(event):
return event['type']
@multimethod('game')
def add_event(event):
print 'GAME'
@multimethod('event')
def add_event(event):
print 'EVENT'
add_event({'type': 'game'}) # prints GAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment