Skip to content

Commit

Permalink
One-off pipes (#94)
Browse files Browse the repository at this point in the history
partial-like syntax for pipe construction
  • Loading branch information
YoraiLevi committed Jan 7, 2024
1 parent 8fed06b commit 2f16935
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,40 @@ optional arguments after:
```


## One-off pipes

Sometimes you just want a one-liner, when creating a pipe you can specify the function's positional and named arguments directly

```python
>>> from itertools import combinations

>>> list(range(5) | Pipe(combinations, 2))
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
>>>
```

a simple running sum with initial starting value

```python
>>> from itertools import accumulate

>>> list(range(10) | Pipe(accumulate, initial=1))
[1, 1, 2, 4, 7, 11, 16, 22, 29, 37, 46]
>>>
```

or filter your data based on some criteria

```python
>>> from itertools import compress

list(range(20) | Pipe(compress, selectors=[1, 0] * 10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> list(range(20) | Pipe(compress, selectors=[0, 1] * 10))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>>
```

## Euler project samples

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

```python
some_iterable | some_pipe(1, 2, 3)
some_iterable | Pipe(some_func, 1, 2, 3)
```

is strictly equivalent to:
Expand Down
6 changes: 4 additions & 2 deletions pipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ class Pipe:
# 2, 4, 6
"""

def __init__(self, function):
self.function = function
def __init__(self, function, *args, **kwargs):
self.function = lambda iterable, *args2, **kwargs2: function(
iterable, *args, *args2, **kwargs, **kwargs2
)
functools.update_wrapper(self, function)

def __ror__(self, other):
Expand Down

0 comments on commit 2f16935

Please sign in to comment.