Last active
May 15, 2016 07:54
-
-
Save yxy/71152b35622cd0ca3544e9363b0d09f8 to your computer and use it in GitHub Desktop.
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
""" | |
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