Last active
December 12, 2015 04:48
-
-
Save inlinestyle/4716761 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
import functools | |
class Registry(object): | |
def __init__(self): | |
self.dispatchers = {} | |
self.functions = defaultdict(dict) | |
def __enter__(self): | |
self.old_registry = multimethod.registry | |
multimethod.registry = self | |
def __exit__(self, *args): | |
multimethod.registry = self.old_registry | |
class multimethod(object): | |
registry = Registry() | |
def __init__(self, dispatch_value): | |
self._dispatch_value = dispatch_value | |
def __call__(self, function): | |
registry = self.registry | |
registry.functions[function.__name__][self._dispatch_value] = function | |
def proxy(*args, **kwargs): | |
dispatch_value = registry.dispatchers[function.__name__](*args, **kwargs) | |
return registry.functions[function.__name__][dispatch_value](*args, **kwargs) | |
return proxy | |
@classmethod | |
def register(cls, name, dispatcher=None): | |
if dispatcher is not None: | |
cls.registry.dispatchers[name] = dispatcher | |
else: | |
return functools.partial(cls.register, name) | |
""" | |
>>> with Registry(): | |
... @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'}) | |
GAME | |
>>> add_event({'type': 'game'}) | |
GAME | |
""" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment