Skip to content

Instantly share code, notes, and snippets.

@built
Created June 10, 2009 21:41
Show Gist options
  • Save built/127520 to your computer and use it in GitHub Desktop.
Save built/127520 to your computer and use it in GitHub Desktop.
#Play with dispatch ideas and guards in Python.
class Guard:
dispatch_table = []
@classmethod
def register(cls, func, condition):
cls.dispatch_table += [(func, condition)]
@classmethod
def satisfies_predicate(cls, predicate, params):
return eval(predicate, params) if predicate else True
def when(condition=""):
def decorator(func):
Guard.register(func, condition)
def dispatcher(**args):
possibles = [method for (method, predicate) in Guard.dispatch_table if method.__name__ == func.__name__ and Guard.satisfies_predicate(predicate, args)]
return possibles[0](**args) if possibles else func(**args)
return dispatcher
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment