Skip to content

Instantly share code, notes, and snippets.

@Kelketek
Last active October 9, 2024 01:25
Show Gist options
  • Save Kelketek/4594314a17c17ed978df6272e0534c1f to your computer and use it in GitHub Desktop.
Save Kelketek/4594314a17c17ed978df6272e0534c1f to your computer and use it in GitHub Desktop.
"""
Demonstration of how one might make an R-like 'piping' operator and set of functions.
"""
class PipeWrapped:
"""
Inner piping class, gets preloaded with the args and kwargs that will be used
with the resultant function. When used as the right-hand of the | operator,
executes the function with the other value as the first argument, and the args and
kwargs passed after.
"""
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __ror__(self, other):
return self.func(other, *self.args, **self.kwargs)
class Pipe:
"""
Class which wraps the function. Calling this will produce a callable PipeWrapped
instance with the args and kwargs prebound.
"""
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return PipeWrapped(self.func, *args, **kwargs)
def pipeable(func):
return Pipe(func)
@pipeable
def reverse_thing(item):
return reversed(item)
@pipeable
def tupilify(item):
return tuple(item)
@pipeable
def append(tup, *args):
return tup + args
# Returns (4, 3, 2, 1, 0, -1, -2)
print((1, 2, 3, 4) | reverse_thing() | tupilify() | append(0, -1, -2))
# Can still be used directly with .func when needed.
# Returns (1, 2, 3, 4, 5, 6)
print(append.func((1, 2, 3), 4, 5, 6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment