Last active
July 26, 2017 15:28
-
-
Save maxpert/72e745fd57c70052e83748f3ae84e302 to your computer and use it in GitHub Desktop.
Python pipe syntactic sugar
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
import inspect | |
class PipeFunction: | |
def __init__(self, func, *args, **kwargs): | |
self._func = func | |
self._args = args | |
self._kwargs = kwargs | |
def __call__(self, *args, **kwargs): | |
return self._append_params(*args, **kwargs) | |
def __or__(self, other): | |
return self.__rshift__(other) | |
def __rshift__(self, other): | |
return self.chain_right(other) | |
def __lshift__(self, other): | |
return self.chain_left(other) | |
def chain_right(self, other): | |
def forward(*args, **kwargs): | |
return other(self(*args, **kwargs).lift()).lift() | |
return PipeFunction(forward) | |
def chain_left(self, other): | |
def reverse(*args, **kwargs): | |
return self(other(*args, **kwargs).lift()).lift() | |
return PipeFunction(reverse) | |
def _append_params(self, *args, **kwargs): | |
new_args = self._args + args | |
new_kwargs = dict(self._kwargs, **kwargs) | |
return PipeFunction(self._func, *new_args, **new_kwargs) | |
def lift(self): | |
return self._func(*self._args, **self._kwargs) | |
class Piped: | |
def __init__(self, func): | |
self._func = func | |
def __call__(self, *args, **kwargs): | |
return PipeFunction(self._func, *args, **kwargs) | |
def __get__(self, instance, owner): | |
return PipeFunction(self._func, instance) | |
@Piped | |
def PipableConstant(v): | |
return v |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment