Skip to content

Commit

Permalink
add possibility to chain pipes before execution
Browse files Browse the repository at this point in the history
- additionally allow subclassing Pipe by using self.__class__ instead of Pipe as constructor
  • Loading branch information
hubald committed Apr 24, 2023
1 parent f9b513e commit 7eaf3fa
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
9 changes: 8 additions & 1 deletion pipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,15 @@ def __init__(self, function):
def __ror__(self, other):
return self.function(other)

def __or__(self, other):
return self.__class__(
lambda iterable, *args2, **kwargs2: other.function(
self.function(iterable, *args2, **kwargs2)
)
)

def __call__(self, *args, **kwargs):
return Pipe(
return self.__class__(
lambda iterable, *args2, **kwargs2: self.function(
iterable, *args, *args2, **kwargs, **kwargs2
)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_pipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,15 @@ def test_enumerate():
data = [4, "abc", {"key": "value"}]
expected = [(5, 4), (6, "abc"), (7, {"key": "value"})]
assert list(data | pipe.enumerate(start=5)) == expected


def test_concatenate_pipes():
data = range(10)
is_even = pipe.where(lambda x: x % 2 == 0)
higher_than_4 = pipe.where(lambda x: x > 4)
expected = [6,8]
# standard behavior
assert list(data | is_even | higher_than_4) == expected
# concatenated pipes
is_even_and_higher_than_4 = is_even | higher_than_4
assert list(data | is_even_and_higher_than_4) == expected

0 comments on commit 7eaf3fa

Please sign in to comment.