Skip to content

Commit 2f16935

Browse files
authored
One-off pipes (#94)
partial-like syntax for pipe construction
1 parent 8fed06b commit 2f16935

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -534,6 +534,40 @@ optional arguments after:
534534
```
535535

536536

537+
## One-off pipes
538+
539+
Sometimes you just want a one-liner, when creating a pipe you can specify the function's positional and named arguments directly
540+
541+
```python
542+
>>> from itertools import combinations
543+
544+
>>> list(range(5) | Pipe(combinations, 2))
545+
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
546+
>>>
547+
```
548+
549+
a simple running sum with initial starting value
550+
551+
```python
552+
>>> from itertools import accumulate
553+
554+
>>> list(range(10) | Pipe(accumulate, initial=1))
555+
[1, 1, 2, 4, 7, 11, 16, 22, 29, 37, 46]
556+
>>>
557+
```
558+
559+
or filter your data based on some criteria
560+
561+
```python
562+
>>> from itertools import compress
563+
564+
list(range(20) | Pipe(compress, selectors=[1, 0] * 10))
565+
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
566+
>>> list(range(20) | Pipe(compress, selectors=[0, 1] * 10))
567+
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
568+
>>>
569+
```
570+
537571
## Euler project samples
538572

539573
> Find the sum of all the multiples of 3 or 5 below 1000.
@@ -578,6 +612,7 @@ For multi-argument pipes then can be partially initialized, you can think of cur
578612

579613
```python
580614
some_iterable | some_pipe(1, 2, 3)
615+
some_iterable | Pipe(some_func, 1, 2, 3)
581616
```
582617

583618
is strictly equivalent to:

pipe.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,10 @@ class Pipe:
3232
# 2, 4, 6
3333
"""
3434

35-
def __init__(self, function):
36-
self.function = function
35+
def __init__(self, function, *args, **kwargs):
36+
self.function = lambda iterable, *args2, **kwargs2: function(
37+
iterable, *args, *args2, **kwargs, **kwargs2
38+
)
3739
functools.update_wrapper(self, function)
3840

3941
def __ror__(self, other):

0 commit comments

Comments
 (0)