Skip to content

Instantly share code, notes, and snippets.

@Ronald-TR
Last active November 20, 2019 12:06
Show Gist options
  • Save Ronald-TR/811d233eaa0ca0f96bda54402f4ffa57 to your computer and use it in GitHub Desktop.
Save Ronald-TR/811d233eaa0ca0f96bda54402f4ffa57 to your computer and use it in GitHub Desktop.
Simple implementation of pipe operator into your functions: https://code.sololearn.com/ca4QB7ZEM91L/#py
"""Cause the fstrings notation into the example 'congrats' functions,
the examples only works in python 3.8.
"""
from functools import partial
class Pipe:
def __init__(self, function):
self.function = function
def __ror__(self, other):
part = None
if isinstance(other, tuple):
part = partial(self.function, *other)
elif isinstance(other, dict):
part = partial(self.function, **other)
else:
part = partial(self.function, other)
return part()
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
@Pipe
def mysum(*elements):
return sum(elements)
@Pipe
def congrats(hello):
return f'{hello=}'
print((1, 2, 3, 4, 5) | mysum)
print({'hello': 'world'} | congrats)
print('world' | congrats)
print(congrats('world'))
# results:
# >> 15
# >> hello='world'
# >> hello='world'
# >> hello='world'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment