Created
June 8, 2015 02:42
-
-
Save tkhoa2711/ff1b2013f60d06fb4c66 to your computer and use it in GitHub Desktop.
A barely simple implementation of multiple-value dispatch for Python
This file contains 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
def valuedispatch(func): | |
""" | |
A simple decorator for multiple dispatch based on values, not types. | |
Transform a function into generic function, which can have different behaviours | |
depending upon the values of its keyword arguments. | |
""" | |
registry = {} | |
def register(**kwargs): | |
""" | |
Register a new implementation for the given *kwargs* on a generic function. | |
""" | |
def decorator(dispatch_fn): | |
registry[frozenset(dict(**kwargs).items())] = dispatch_fn | |
return dispatch_fn | |
return decorator | |
def dispatch(**kwargs): | |
""" | |
Dispatch the available implementation for the given *kwargs*. | |
""" | |
key = frozenset(dict(**kwargs).items()) | |
return registry.get(key, func) | |
def wrapper(*args, **kwargs): | |
return dispatch(**kwargs)(*args, **kwargs) | |
wrapper.registry = registry | |
wrapper.register = register | |
wrapper.dispatch = dispatch | |
update_wrapper(wrapper, func) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment