Skip to content

Instantly share code, notes, and snippets.

@Silva97
Created March 28, 2023 13:59
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 Silva97/29214fbb2ee8afe48a91b0246531c7b1 to your computer and use it in GitHub Desktop.
Save Silva97/29214fbb2ee8afe48a91b0246531c7b1 to your computer and use it in GitHub Desktop.
Class to create a wrapper to pipe function calls.
import inspect
class Pipe:
"""
Create a wrapper to pipe function calls with the given value.
The functions could be: value's method, builtin or any
function in the current module.
Examples:
print(254 | Pipe() | hex | str.upper)
print(Pipe(254) | hex | str.upper)
print((254 | Pipe() | hex).upper())
print(Pipe(254).hex().upper())
Author: Luiz Felipe Silva (https://github.com/Silva97)
"""
__value = None
__withAttribute = None
def __init__(self, value=None, withAttribute: str = None):
self.__value = value
self.__withAttribute = withAttribute
def unpipe(self):
""" Get the raw value without the Pipe wrapper """
if self.__withAttribute != None:
return getattr(self.__value, self.__withAttribute)
return self.__value
def __getattr__(self, name):
self.__withAttribute = name
return self
def __call__(self, *args):
function = self.__withAttribute
self.__withAttribute = None
if hasattr(self.__value, function):
self.__value = getattr(self.__value, function)(*args)
return self
builtinModule = __import__('builtins')
if hasattr(builtinModule, function):
function = getattr(builtinModule, function)
self.__value = function(self.__value, *args)
return self
callerModuleName = inspect.currentframe().f_back.f_globals.get('__name__')
callerModule = __import__(callerModuleName)
if hasattr(callerModule, function):
function = getattr(callerModule, function)
self.__value = function(self.__value, *args)
return self
raise Exception(
f"Function '{function}' could not be found.")
def __ror__(self, value):
self.__value = value
return self
def __or__(self, function):
self.__value = function(self.__value)
return self
def __bool__(self):
return bool(self.unpipe())
def __int__(self):
return int(self.unpipe())
def __float__(self):
return float(self.unpipe())
def __str__(self):
return str(self.unpipe())
def __bytes__(self):
return bytes(self.unpipe())
def __hash__(self):
return hash(self.unpipe())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment