Skip to content

Instantly share code, notes, and snippets.

@PapyrusThePlant
Created January 24, 2017 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PapyrusThePlant/e980a7ee5ea0dfb6edb97de6f0650199 to your computer and use it in GitHub Desktop.
Save PapyrusThePlant/e980a7ee5ea0dfb6edb97de6f0650199 to your computer and use it in GitHub Desktop.
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