Created
July 7, 2015 21:55
-
-
Save edelvalle/67162cbaff3e1582890b to your computer and use it in GitHub Desktop.
where prototype
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
from functools import wraps | |
class where(object): | |
def __init__(self, function, predicate): | |
self._alternatives = [] | |
self.where(predicate)(function) | |
def where(self, predicate): | |
def decorator(function): | |
self._alternatives.append((function, predicate)) | |
return wraps(function)(self) | |
return decorator | |
def otherwise(self, function): | |
self._alternatives.append((function, lambda *args, **kwargs: True)) | |
return self | |
def __call__(self, *args, **kwargs): | |
for function, predicate in self._alternatives: | |
try: | |
valid = predicate(*args, **kwargs) | |
except TypeError: | |
valid = False | |
if valid: | |
return function(*args, **kwargs) | |
raise ValueError( | |
'Invalid arguments args: %s, kwargs: %s' % (args, kwargs) | |
) | |
def carga(predicate): | |
def decorator(function): | |
return where(function, predicate) | |
return decorator | |
@carga(lambda x: x > 2) | |
def cosa(x): | |
print('X mayor 2') | |
@cosa.where(lambda x: x == 1) | |
def cosa(x): | |
print('X es 1') | |
@cosa.otherwise | |
def cosa(x): | |
print('X es una cosa') | |
cosa(3) | |
cosa(1) | |
cosa('Otjer') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment