Skip to content

Instantly share code, notes, and snippets.

@yxy
Last active May 15, 2016 07:54
Show Gist options
  • Save yxy/71152b35622cd0ca3544e9363b0d09f8 to your computer and use it in GitHub Desktop.
Save yxy/71152b35622cd0ca3544e9363b0d09f8 to your computer and use it in GitHub Desktop.
"""
A mutlimethod decorator, dispatch based on the input types.
"""
registry = {}
def multimethod(*types):
def wrapper(fn):
# registry key=>func
_types = tuple(t for t in types)
registry[_types] = fn
def _wrapper(*args):
__types = tuple(t.__class__ for t in args)
return registry[__types](*args)
return _wrapper
return wrapper
@multimethod(int, int)
def foo(a, b):
print("int int")
@multimethod(float, float)
def foo(a, b):
print("float float")
foo(1, 2)
foo(1.0, 2.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment