Created
June 10, 2009 21:41
-
-
Save built/127520 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
#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