Skip to content

Commit 7eaf3fa

Browse files
committed
add possibility to chain pipes before execution
- additionally allow subclassing Pipe by using self.__class__ instead of Pipe as constructor
1 parent f9b513e commit 7eaf3fa

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

pipe.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,15 @@ def __init__(self, function):
3939
def __ror__(self, other):
4040
return self.function(other)
4141

42+
def __or__(self, other):
43+
return self.__class__(
44+
lambda iterable, *args2, **kwargs2: other.function(
45+
self.function(iterable, *args2, **kwargs2)
46+
)
47+
)
48+
4249
def __call__(self, *args, **kwargs):
43-
return Pipe(
50+
return self.__class__(
4451
lambda iterable, *args2, **kwargs2: self.function(
4552
iterable, *args, *args2, **kwargs, **kwargs2
4653
)

tests/test_pipe.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,15 @@ def test_enumerate():
3838
data = [4, "abc", {"key": "value"}]
3939
expected = [(5, 4), (6, "abc"), (7, {"key": "value"})]
4040
assert list(data | pipe.enumerate(start=5)) == expected
41+
42+
43+
def test_concatenate_pipes():
44+
data = range(10)
45+
is_even = pipe.where(lambda x: x % 2 == 0)
46+
higher_than_4 = pipe.where(lambda x: x > 4)
47+
expected = [6,8]
48+
# standard behavior
49+
assert list(data | is_even | higher_than_4) == expected
50+
# concatenated pipes
51+
is_even_and_higher_than_4 = is_even | higher_than_4
52+
assert list(data | is_even_and_higher_than_4) == expected

0 commit comments

Comments
 (0)