Browse Source

startup: add class PipeFilter

Fabian Peter Hammerle 1 month ago
parent
commit
220abc869d
1 changed files with 13 additions and 0 deletions
  1. 13 0
      profile_default/startup/init.py

+ 13 - 0
profile_default/startup/init.py

@@ -204,6 +204,19 @@ assert "123|456\n98|76|54".splitlines() | PipeMap(lambda s: s.split("|")) | Pipe
 ]
 
 
+class PipeFilter(Pipe):
+    def __init__(
+        self, filter_function: typing.Union[typing.Callable[[typing.Any], bool], None]
+    ) -> None:
+        self._function = functools.partial(filter, filter_function)
+
+
+assert range(5) | PipeFilter(lambda n: n % 2 == 0) | Pipe(list) == [0, 2, 4]
+assert [0, True, 2.3, "4", (5, 6)] | PipeFilter(
+    lambda e: isinstance(e, (bool, tuple))
+) | Pipe(list) == [True, (5, 6)]
+
+
 class PipePair(PipeMap):
     def __init__(
         self, function: typing.Callable[[typing.Any], typing.Any], axis: int = 0