Last active
February 26, 2022 13:18
-
-
Save runekaagaard/5a172eccfa2fdbcd625a3a0ebe71ea79 to your computer and use it in GitHub Desktop.
pipe operator in python.
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
from functools import wraps | |
class Ror: | |
def __init__(self, func, args, kwargs): | |
self.func = func | |
self.args = args | |
self.kwargs = kwargs | |
def __ror__(self, arg): | |
return self.func(arg, *self.args, **self.kwargs) | |
def pipeable(f): | |
@wraps(f) | |
def _(*args, **kwargs): | |
if f.__code__.co_argcount - 1 == len(args): | |
return Ror(f, args, kwargs) | |
else: | |
return f(*args, **kwargs) | |
return _ | |
@pipeable | |
def psum(numbers): | |
return sum(numbers) | |
@pipeable | |
def ppow(n, power): | |
return n**power | |
print("Normal:", ppow(psum([1, 2, 3]), 10)) | |
print(" Piped:", [1, 2, 3] | psum() | ppow(10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment