-
-
Save beng/4589615 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
# coding: utf8 | |
"""Simple pattern matching function dispatch through a decorator | |
Example: | |
@matchs(int) | |
def myfunc(i): | |
print "int received:", i | |
@matchs(str): | |
def myfunc(s): | |
print "str received:", s | |
myfunc(1) | |
myfunc("s") | |
""" | |
class PatternMatchingError(Exception): | |
"Raised when there is not matching pattern" | |
class PatternHandler(object): | |
"Function cache and dispatcher" | |
cache = {} | |
def __init__(self, f, *args, **kwargs): | |
"Store the function and its signature in the cache" | |
kwargs_tuple = tuple(kwargs.items()) | |
fname = self.__name__ = f.__name__ | |
self.cache[(fname, args, kwargs_tuple)] = f | |
def __call__(self, *args, **kwargs): | |
"Dispatch to the proper function" | |
args_t = tuple(type(t) for t in args) | |
kwargs_t = tuple((name, type(t)) for name, t in kwargs.items()) | |
fname = self.__name__ | |
func = self.cache.get((fname, args_t, kwargs_t), None) | |
if not func: | |
raise PatternMatchingError("Function not found") | |
return func(*args, **kwargs) | |
def matchs(*args, **kwargs): | |
"Declare that a function handles a pattern" | |
def decorator(f): | |
return PatternHandler(f, *args, **kwargs) | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment