Last active
June 12, 2020 22:23
-
-
Save bofm/f58d356a2f607e7cb321810e488e0bfa to your computer and use it in GitHub Desktop.
Python compose picklable
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
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