Skip to content

Instantly share code, notes, and snippets.

@bofm
Last active June 12, 2020 22:23
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 bofm/f58d356a2f607e7cb321810e488e0bfa to your computer and use it in GitHub Desktop.
Save bofm/f58d356a2f607e7cb321810e488e0bfa to your computer and use it in GitHub Desktop.
Python compose picklable
class compose:
__slots__ = ('f', 'fs')
def __init__(self, *fs):
self.f, *self.fs = reversed(fs)
def __call__(self, *args, **kwargs):
result = self.f(*args, **kwargs)
for f in self.fs:
result = f(result)
return result
def _compose(self, f):
return compose(self, f)
__mul__ = _compose
__lshift__ = __call__
def id_(x):
return x
C = compose(id_)
# >>> compose(str.upper, ','.join, str.split)(' ab cd xy z ')
# 'AB,CD,XY,Z'
# >>> C * str.upper * ','.join * str.split << ' ab cd xy z '
# 'AB,CD,XY,Z'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment