Skip to content

Instantly share code, notes, and snippets.

@tkhoa2711
Created June 8, 2015 02:42
Show Gist options
  • Save tkhoa2711/ff1b2013f60d06fb4c66 to your computer and use it in GitHub Desktop.
Save tkhoa2711/ff1b2013f60d06fb4c66 to your computer and use it in GitHub Desktop.
A barely simple implementation of multiple-value dispatch for Python
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