Skip to content

Instantly share code, notes, and snippets.

@beng
Forked from rbistolfi/pmatching.py
Created January 21, 2013 21:30
Show Gist options
  • Save beng/4589615 to your computer and use it in GitHub Desktop.
Save beng/4589615 to your computer and use it in GitHub Desktop.
# 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