Created
January 24, 2017 14:55
-
-
Save PapyrusThePlant/e980a7ee5ea0dfb6edb97de6f0650199 to your computer and use it in GitHub Desktop.
This file contains 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
class Composition: | |
def __init__(self, *funcs): | |
self._funcs = [*funcs] | |
def append(self, obj): | |
if isinstance(obj, Composition): | |
self._funcs.extend(obj._funcs) | |
elif callable(obj): | |
self._funcs.append(obj) | |
else: | |
raise RuntimeError('Only Composition instances or callable objects can be appended to a class Composition.') | |
def prepend(self, obj): | |
if isinstance(obj, Composition): | |
for func in obj._funcs: | |
self._funcs.insert(0, func) | |
elif callable(obj): | |
self._funcs.insert(0, obj) | |
else: | |
raise RuntimeError('Only Composition instances or callable objects can be appended to a class Composition.') | |
def __call__(self, *args, **kwargs): | |
res = self._funcs[0](*args, **kwargs) | |
for func in self._funcs[1:]: | |
res = func(res) | |
return res | |
def __rshift__(self, other): | |
# self >> other | |
self.append(other) | |
return self | |
def __lshift__(self, other): | |
# self << other | |
self.prepend(other) | |
return self | |
class ComposableFunc: | |
def __init__(self, func): | |
self.name = func.__name__ | |
self.func = func | |
def __rshift__(self, other): | |
# self >> other | |
if isinstance(other, Composition): | |
other.prepend(self) | |
return other | |
else: | |
return Composition(self, other) | |
def __lshift__(self, other): | |
# self << other | |
if isinstance(other, Composition): | |
other.append(self) | |
return other | |
else: | |
return Composition(other, self) | |
def __call__(self, *args, **kwargs): | |
return self.func(*args, **kwargs) | |
def composable(func): | |
return ComposableFunc(func) | |
@composable | |
def ca(val): | |
print('ca', val) | |
return 'yay !' | |
@composable | |
def cb(val): | |
print('cb', val) | |
return val + 100 | |
@composable | |
def cc(val1, val2, valk=None): | |
print('cc', val1, val2, valk) | |
return 20 | |
cd = ca << cb << cc | |
cd = cc >> cb >> ca | |
cd = cb << cc >> ca | |
print(cd(10, 11, valk='hi')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment