From 7eaf3fa937e918ea2fb44b930da335dc168591e3 Mon Sep 17 00:00:00 2001 From: hubald <5376779+hubald@users.noreply.github.com> Date: Mon, 24 Apr 2023 09:56:52 +0200 Subject: [PATCH] add possibility to chain pipes before execution - additionally allow subclassing Pipe by using self.__class__ instead of Pipe as constructor --- pipe.py | 9 ++++++++- tests/test_pipe.py | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/pipe.py b/pipe.py index f6d24ef..681c9ac 100644 --- a/pipe.py +++ b/pipe.py @@ -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 ) diff --git a/tests/test_pipe.py b/tests/test_pipe.py index 8bba1c9..e47e41c 100644 --- a/tests/test_pipe.py +++ b/tests/test_pipe.py @@ -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