Name | pipe JSON |
Version |
2.2
JSON |
| download |
home_page | None |
Summary | Module enabling a sh like infix syntax (using pipes) |
upload_time | 2024-04-04 06:37:17 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.8 |
license | MIT License |
keywords |
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# Pipe — Infix programming toolkit
[


](https://pypi.org/project/pipe)
[](https://github.com/JulienPalard/pipe/actions)
Module enabling a sh like infix syntax (using pipes).
# Introduction
As an example, here is the solution for the [2nd Euler Project
problem](https://projecteuler.net/problem=2):
> Find the sum of all the even-valued terms in Fibonacci which do not
exceed four million.
Given `fib` a generator of Fibonacci numbers:
```python
sum(fib() | where(lambda x: x % 2 == 0) | take_while(lambda x: x < 4000000))
```
Each pipes is lazy evalatated, can be aliased, and partially
initialized, so it could be rewritten as:
```python
is_even = where(lambda x: x % 2 == 0)
sum(fib() | is_even | take_while(lambda x: x < 4000000)
```
# Installing
To install the library, you can just run the following command:
```shell
# Linux/macOS
python3 -m pip install pipe
# Windows
py -3 -m pip install pipe
```
# Using
The basic syntax is to use a `|` like in a shell:
```python
>>> from itertools import count
>>> from pipe import select, take
>>> sum(count() | select(lambda x: x ** 2) | take(10))
285
>>>
```
Some pipes take an argument:
```python
>>> from pipe import where
>>> sum([1, 2, 3, 4] | where(lambda x: x % 2 == 0))
6
>>>
```
Some do not need one:
```python
>>> from pipe import traverse
>>> for i in [1, [2, 3], 4] | traverse:
... print(i)
1
2
3
4
>>>
```
In which case it's allowed to use the calling parenthesis:
```python
>>> from pipe import traverse
>>> for i in [1, [2, 3], 4] | traverse():
... print(i)
1
2
3
4
>>>
```
## Existing Pipes in this module
Alphabetical list of available pipes; when several names are listed
for a given pipe, these are aliases.
### `batched`
Like Python 3.12 `itertool.batched`:
```python
>>> from pipe import batched
>>> list("ABCDEFG" | batched(3))
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
>>>
```
### `chain`
Chain a sequence of iterables:
```python
>>> from pipe import chain
>>> list([[1, 2], [3, 4], [5]] | chain)
[1, 2, 3, 4, 5]
>>>
```
Warning : chain only unfold iterable containing ONLY iterables:
```python
[1, 2, [3]] | chain
```
Gives a `TypeError: chain argument #1 must support iteration`
Consider using traverse.
### `chain_with(other)`
Like itertools.chain, yields elements of the given iterable,
then yields elements of its parameters
```python
>>> from pipe import chain_with
>>> list((1, 2, 3) | chain_with([4, 5], [6]))
[1, 2, 3, 4, 5, 6]
>>>
```
### `dedup(key=None)`
Deduplicate values, using the given `key` function if provided.
```python
>>> from pipe import dedup
>>> list([-1, 0, 0, 0, 1, 2, 3] | dedup)
[-1, 0, 1, 2, 3]
>>> list([-1, 0, 0, 0, 1, 2, 3] | dedup(key=abs))
[-1, 0, 2, 3]
>>>
```
### `enumerate(start=0)`
The builtin `enumerate()` as a Pipe:
```python
>>> from pipe import enumerate
>>> list(['apple', 'banana', 'citron'] | enumerate)
[(0, 'apple'), (1, 'banana'), (2, 'citron')]
>>> list(['car', 'truck', 'motorcycle', 'bus', 'train'] | enumerate(start=6))
[(6, 'car'), (7, 'truck'), (8, 'motorcycle'), (9, 'bus'), (10, 'train')]
>>>
```
### `filter(predicate)`
Alias for `where(predicate)`, see `where(predicate)`.
### `groupby(key=None)`
Like `itertools.groupby(sorted(iterable, key = keyfunc), keyfunc)`
```python
>>> from pipe import groupby, map
>>> items = range(10)
>>> ' / '.join(items | groupby(lambda x: "Odd" if x % 2 else "Even")
... | select(lambda x: "{}: {}".format(x[0], ', '.join(x[1] | map(str)))))
'Even: 0, 2, 4, 6, 8 / Odd: 1, 3, 5, 7, 9'
>>>
```
### `islice()`
Just the `itertools.islice` function as a Pipe:
```python
>>> from pipe import islice
>>> list((1, 2, 3, 4, 5, 6, 7, 8, 9) | islice(2, 8, 2))
[3, 5, 7]
>>>
```
### `izip()`
Just the `itertools.izip` function as a Pipe:
```python
>>> from pipe import izip
>>> list(range(0, 10) | izip(range(1, 11)))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]
>>>
```
### `map()`, `select()`
Apply a conversion expression given as parameter
to each element of the given iterable
```python
>>> list([1, 2, 3] | map(lambda x: x * x))
[1, 4, 9]
>>> list([1, 2, 3] | select(lambda x: x * x))
[1, 4, 9]
>>>
```
### `netcat`
The netcat Pipe sends and receive bytes over TCP:
```python
data = [
b"HEAD / HTTP/1.0\r\n",
b"Host: python.org\r\n",
b"\r\n",
]
for packet in data | netcat("python.org", 80):
print(packet.decode("UTF-8"))
```
Gives:
```
HTTP/1.1 301 Moved Permanently
Content-length: 0
Location: https://python.org/
Connection: close
```
### ```permutations(r=None)```
Returns all possible permutations:
```python
>>> from pipe import permutations
>>> for item in 'ABC' | permutations(2):
... print(item)
('A', 'B')
('A', 'C')
('B', 'A')
('B', 'C')
('C', 'A')
('C', 'B')
>>>
```
```python
>>> for item in range(3) | permutations:
... print(item)
(0, 1, 2)
(0, 2, 1)
(1, 0, 2)
(1, 2, 0)
(2, 0, 1)
(2, 1, 0)
>>>
```
### `reverse`
Like Python's built-in `reversed` function.
```python
>>> from pipe import reverse
>>> list([1, 2, 3] | reverse)
[3, 2, 1]
>>>
```
### `select(fct)`
Alias for `map(fct)`, see `map(fct)`.
### `skip()`
Skips the given quantity of elements from the given iterable, then yields
```python
>>> from pipe import skip
>>> list((1, 2, 3, 4, 5) | skip(2))
[3, 4, 5]
>>>
```
### `skip_while(predicate)`
Like itertools.dropwhile, skips elements of the given iterable
while the predicate is true, then yields others:
```python
>>> from pipe import skip_while
>>> list([1, 2, 3, 4] | skip_while(lambda x: x < 3))
[3, 4]
>>>
```
### `sort(key=None, reverse=False)`
Like Python's built-in "sorted" primitive.
```python
>>> from pipe import sort
>>> ''.join("python" | sort)
'hnopty'
>>> [5, -4, 3, -2, 1] | sort(key=abs)
[1, -2, 3, -4, 5]
>>>
```
### `t`
Like Haskell's operator ":":
```python
>>> from pipe import t
>>> for i in 0 | t(1) | t(2):
... print(i)
0
1
2
>>>
```
### `tail(n)`
Yields the given quantity of the last elements of the given iterable.
```python
>>> from pipe import tail
>>> for i in (1, 2, 3, 4, 5) | tail(3):
... print(i)
3
4
5
>>>
```
### `take(n)`
Yields the given quantity of elements from the given iterable, like `head`
in shell script.
```python
>>> from pipe import take
>>> for i in count() | take(5):
... print(i)
0
1
2
3
4
>>>
```
### `take_while(predicate)`
Like `itertools.takewhile`, yields elements of the
given iterable while the predicate is true:
```python
>>> from pipe import take_while
>>> for i in count() | take_while(lambda x: x ** 2 < 100):
... print(i)
0
1
2
3
4
5
6
7
8
9
>>>
```
### `tee`
tee outputs to the standard output and yield unchanged items, useful for
debugging a pipe stage by stage:
```python
>>> from pipe import tee
>>> sum(["1", "2", "3", "4", "5"] | tee | map(int) | tee)
'1'
1
'2'
2
'3'
3
'4'
4
'5'
5
15
>>>
```
The `15` at the end is the `sum` returning.
### `transpose()`
Transposes the rows and columns of a matrix.
```python
>>> from pipe import transpose
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | transpose
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>>
```
### `traverse`
Recursively unfold iterables:
```python
>>> list([[1, 2], [[[3], [[4]]], [5]]] | traverse)
[1, 2, 3, 4, 5]
>>> squares = (i * i for i in range(3))
>>> list([[0, 1, 2], squares] | traverse)
[0, 1, 2, 0, 1, 4]
>>>
```
### `uniq(key=None)`
Like dedup() but only deduplicate consecutive values, using the given
`key` function if provided (or else the identity).
```python
>>> from pipe import uniq
>>> list([1, 1, 2, 2, 3, 3, 1, 2, 3] | uniq)
[1, 2, 3, 1, 2, 3]
>>> list([1, -1, 1, 2, -2, 2, 3, 3, 1, 2, 3] | uniq(key=abs))
[1, 2, 3, 1, 2, 3]
>>>
```
### `where(predicate)`, `filter(predicate)`
Only yields the matching items of the given iterable:
```python
>>> list([1, 2, 3] | where(lambda x: x % 2 == 0))
[2]
>>>
```
Don't forget they can be aliased:
```python
>>> positive = where(lambda x: x > 0)
>>> negative = where(lambda x: x < 0)
>>> sum([-10, -5, 0, 5, 10] | positive)
15
>>> sum([-10, -5, 0, 5, 10] | negative)
-15
>>>
```
## Constructing your own
You can construct your pipes using the `Pipe` class like:
```python
from pipe import Pipe
square = Pipe(lambda iterable: (x ** 2 for x in iterable))
map = Pipe(lambda iterable, fct: builtins.map(fct, iterable)
>>>
```
As you can see it's often very short to write, and with a bit of luck
the function you're wrapping already takes an iterable as the first
argument, making the wrapping straight forward:
```python
>>> from collections import deque
>>> from pipe import Pipe
>>> end = Pipe(deque)
>>>
```
and that's it `itrable | end(3)` is `deque(iterable, 3)`:
```python
>>> list(range(100) | end(3))
[97, 98, 99]
>>>
```
In case it gets more complicated one can use `Pipe` as a decorator to
a function taking an iterable as the first argument, and any other
optional arguments after:
```python
>>> from statistics import mean
>>> @Pipe
... def running_average(iterable, width):
... items = deque(maxlen=width)
... for item in iterable:
... items.append(item)
... yield mean(items)
>>> list(range(20) | running_average(width=2))
[0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5]
>>> list(range(20) | running_average(width=10))
[0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5]
>>>
```
## 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.
```python
>>> sum(count() | where(lambda x: x % 3 == 0 or x % 5 == 0) | take_while(lambda x: x < 1000))
233168
>>>
```
> Find the sum of all the even-valued terms in Fibonacci which do not
> exceed four million.
```python
sum(fib() | where(lambda x: x % 2 == 0) | take_while(lambda x: x < 4000000))
```
> Find the difference between the sum of the squares of the first one
> hundred natural numbers and the square of the sum.
```python
>>> square = map(lambda x: x ** 2)
>>> sum(range(101)) ** 2 - sum(range(101) | square)
25164150
>>>
```
# Going deeper
## Partial Pipes
A `pipe` can be parametrized without being evaluated:
```python
>>> running_average_of_two = running_average(2)
>>> list(range(20) | running_average_of_two)
[0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5]
>>>
```
For multi-argument pipes then can be partially initialized, you can think of curying:
```python
some_iterable | some_pipe(1, 2, 3)
some_iterable | Pipe(some_func, 1, 2, 3)
```
is strictly equivalent to:
```python
some_iterable | some_pipe(1)(2)(3)
```
So it can be used to specialize pipes, first a dummy example:
```python
>>> @Pipe
... def addmul(iterable, to_add, to_mul):
... """Computes (x + to_add) * to_mul to every items of the input."""
... for i in iterable:
... yield (i + to_add) * to_mul
>>> mul = addmul(0) # This partially initialize addmul with to_add=0
>>> list(range(10) | mul(10))
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
```
Which also works with keyword arguments:
```python
>>> add = addmul(to_mul=1) # This partially initialize addmul with `to_mul=1`
>>> list(range(10) | add(10))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>
```
But now for something interesting:
```python
>>> import re
>>> @Pipe
... def grep(iterable, pattern, flags=0):
... for line in iterable:
... if re.match(pattern, line, flags=flags):
... yield line
...
>>> lines = ["Hello", "hello", "World", "world"]
>>> for line in lines | grep("H"):
... print(line)
Hello
>>>
```
Now let's reuse it in two ways, first with a pattern:
```python
>>> lowercase_only = grep("[a-z]+$")
>>> for line in lines | lowercase_only:
... print(line)
hello
world
>>>
```
Or now with a flag:
```python
>>> igrep = grep(flags=re.IGNORECASE)
>>> for line in lines | igrep("hello"):
... print(line)
...
Hello
hello
>>>
```
## Lazy evaluation
Pipe uses generators all the way down, so it is naturally lazy.
In the following examples we'll use
[itertools.count](https://docs.python.org/fr/3/library/itertools.html#itertools.count):
an infinite generator of integers.
We'll make use of the `tee` pipe too, which prints every values that
passe through it.
The following example does nothing, nothing is printed by `tee` so no
value passed through it. It's nice because generating an infinite
sequence of squares is "slow".
```python
>>> result = count() | tee | select(lambda x: x ** 2)
>>>
```
Chaining more pipes still won't make previous ones start generating
values, in the following example not a single value is pulled out of
`count`:
```python
>>> result = count() | tee | select(lambda x: x ** 2)
>>> first_results = result | take(10)
>>> only_odd_ones = first_results | where(lambda x: x % 2)
>>>
```
Same without variables:
```python
>>> result = (count() | tee
... | select(lambda x: x ** 2)
... | take(10)
... | where(lambda x: x % 2))
>>>
```
Only when values are actually needed, the generators starts to work.
In the following example only two values will be extracted out of `count`:
- `0` which is squared (to `0`), passes the `take(10)` eaily,
but is dropped by `where`
- `1` which is squared (to `1`), also easily passes the `take(10)`,
passes the `where`, and passes the `take(1)`.
At this point `take(1)` is satisfied so no other computations need to
be done. Notice `tee` printing `0` and `1` passing through it:
```python
>>> result = (count() | tee
... | select(lambda x: x ** 2)
... | take(10)
... | where(lambda x: x % 2))
>>> print(list(result | take(1)))
0
1
[1]
>>>
```
## Deprecations
In pipe 1.x a lot of functions were returning iterables and a lot
other functions were returning non-iterables, causing confusion. The
one returning non-iterables could only be used as the last function of
a pipe expression, so they are in fact useless:
```python
range(100) | where(lambda x: x % 2 == 0) | add
```
can be rewritten with no less readability as:
```python
sum(range(100) | where(lambda x: x % 2 == 0))
```
so all pipes returning non-iterables were deprecated (raising
warnings), and finally removed in pipe 2.0.
## What should I do?
Oh, you just upgraded pipe, got an exception, and landed here? You
have three solutions:
1) Stop using closing-pipes, replace `...|...|...|...|as_list` to
`list(...|...|...|)`, that's it, it's even shorter.
2) If "closing pipes" are not an issue for you, and you really like
them, just reimplement the few you really need, it often take a very
few lines of code, or copy them from
[here](https://github.com/JulienPalard/Pipe/blob/dd179c8ff0aa28ee0524f3247e5cb1c51347cba6/pipe.py).
3) If you still rely on a lot of them and are in a hurry, just `pip install pipe<2`.
And start testing your project using the [Python Development
Mode](https://docs.python.org/3/library/devmode.html) so you catch
those warnings before they bite you.
## But I like them, pleassssse, reintroduce them!
This has already been discussed in [#74](https://github.com/JulienPalard/Pipe/issues/74).
An `@Pipe` is often easily implemented in a 1 to 3 lines of code
function, and the `pipe` module does not aim at giving all
possibilities, it aims at giving the `Pipe` decorator.
So if you need more pipes, closing pipes, weird pipes, you-name-it,
feel free to implement them on your project, and consider the
already-implemented ones as examples on how to do it.
See the `Constructing your own` paragraph below.
Raw data
{
"_id": null,
"home_page": null,
"name": "pipe",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": null,
"author": null,
"author_email": "Julien Palard <julien@palard.fr>",
"download_url": "https://files.pythonhosted.org/packages/53/37/aef2cba01787ad8bd266705a95c23db0e9d0b7cd0e01582c969143892655/pipe-2.2.tar.gz",
"platform": null,
"description": "# Pipe \u2014 Infix programming toolkit\n\n[\n \n \n](https://pypi.org/project/pipe)\n[](https://github.com/JulienPalard/pipe/actions)\n\nModule enabling a sh like infix syntax (using pipes).\n\n\n# Introduction\n\nAs an example, here is the solution for the [2nd Euler Project\nproblem](https://projecteuler.net/problem=2):\n\n> Find the sum of all the even-valued terms in Fibonacci which do not\n exceed four million.\n\nGiven `fib` a generator of Fibonacci numbers:\n\n```python\nsum(fib() | where(lambda x: x % 2 == 0) | take_while(lambda x: x < 4000000))\n```\n\nEach pipes is lazy evalatated, can be aliased, and partially\ninitialized, so it could be rewritten as:\n\n```python\nis_even = where(lambda x: x % 2 == 0)\nsum(fib() | is_even | take_while(lambda x: x < 4000000)\n```\n\n\n# Installing\n\nTo install the library, you can just run the following command:\n\n```shell\n# Linux/macOS\npython3 -m pip install pipe\n\n# Windows\npy -3 -m pip install pipe\n```\n\n\n# Using\n\nThe basic syntax is to use a `|` like in a shell:\n\n```python\n>>> from itertools import count\n>>> from pipe import select, take\n>>> sum(count() | select(lambda x: x ** 2) | take(10))\n285\n>>>\n```\n\nSome pipes take an argument:\n\n```python\n>>> from pipe import where\n>>> sum([1, 2, 3, 4] | where(lambda x: x % 2 == 0))\n6\n>>>\n```\n\nSome do not need one:\n\n```python\n>>> from pipe import traverse\n>>> for i in [1, [2, 3], 4] | traverse:\n... print(i)\n1\n2\n3\n4\n>>>\n```\n\nIn which case it's allowed to use the calling parenthesis:\n\n```python\n>>> from pipe import traverse\n>>> for i in [1, [2, 3], 4] | traverse():\n... print(i)\n1\n2\n3\n4\n>>>\n```\n\n\n## Existing Pipes in this module\n\nAlphabetical list of available pipes; when several names are listed\nfor a given pipe, these are aliases.\n\n### `batched`\n\nLike Python 3.12 `itertool.batched`:\n\n```python\n>>> from pipe import batched\n>>> list(\"ABCDEFG\" | batched(3))\n[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]\n>>>\n```\n\n### `chain`\n\nChain a sequence of iterables:\n\n```python\n>>> from pipe import chain\n>>> list([[1, 2], [3, 4], [5]] | chain)\n[1, 2, 3, 4, 5]\n>>>\n```\n\nWarning : chain only unfold iterable containing ONLY iterables:\n\n```python\n[1, 2, [3]] | chain\n```\nGives a `TypeError: chain argument #1 must support iteration`\nConsider using traverse.\n\n\n### `chain_with(other)`\n\nLike itertools.chain, yields elements of the given iterable,\nthen yields elements of its parameters\n\n```python\n>>> from pipe import chain_with\n>>> list((1, 2, 3) | chain_with([4, 5], [6]))\n[1, 2, 3, 4, 5, 6]\n>>>\n```\n\n### `dedup(key=None)`\n\nDeduplicate values, using the given `key` function if provided.\n\n```python\n>>> from pipe import dedup\n>>> list([-1, 0, 0, 0, 1, 2, 3] | dedup)\n[-1, 0, 1, 2, 3]\n>>> list([-1, 0, 0, 0, 1, 2, 3] | dedup(key=abs))\n[-1, 0, 2, 3]\n>>>\n```\n\n\n### `enumerate(start=0)`\n\nThe builtin `enumerate()` as a Pipe:\n\n```python\n>>> from pipe import enumerate\n>>> list(['apple', 'banana', 'citron'] | enumerate)\n[(0, 'apple'), (1, 'banana'), (2, 'citron')]\n>>> list(['car', 'truck', 'motorcycle', 'bus', 'train'] | enumerate(start=6))\n[(6, 'car'), (7, 'truck'), (8, 'motorcycle'), (9, 'bus'), (10, 'train')]\n>>>\n```\n\n\n### `filter(predicate)`\n\nAlias for `where(predicate)`, see `where(predicate)`.\n\n\n### `groupby(key=None)`\n\nLike `itertools.groupby(sorted(iterable, key = keyfunc), keyfunc)`\n\n```python\n>>> from pipe import groupby, map\n>>> items = range(10)\n>>> ' / '.join(items | groupby(lambda x: \"Odd\" if x % 2 else \"Even\")\n... | select(lambda x: \"{}: {}\".format(x[0], ', '.join(x[1] | map(str)))))\n'Even: 0, 2, 4, 6, 8 / Odd: 1, 3, 5, 7, 9'\n>>>\n```\n\n\n### `islice()`\n\nJust the `itertools.islice` function as a Pipe:\n\n```python\n>>> from pipe import islice\n>>> list((1, 2, 3, 4, 5, 6, 7, 8, 9) | islice(2, 8, 2))\n[3, 5, 7]\n>>>\n```\n\n### `izip()`\n\nJust the `itertools.izip` function as a Pipe:\n\n```python\n>>> from pipe import izip\n>>> list(range(0, 10) | izip(range(1, 11)))\n[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10)]\n>>>\n```\n\n### `map()`, `select()`\n\nApply a conversion expression given as parameter\nto each element of the given iterable\n\n```python\n>>> list([1, 2, 3] | map(lambda x: x * x))\n[1, 4, 9]\n\n>>> list([1, 2, 3] | select(lambda x: x * x))\n[1, 4, 9]\n>>>\n```\n\n### `netcat`\n\nThe netcat Pipe sends and receive bytes over TCP:\n\n```python\ndata = [\n b\"HEAD / HTTP/1.0\\r\\n\",\n b\"Host: python.org\\r\\n\",\n b\"\\r\\n\",\n]\nfor packet in data | netcat(\"python.org\", 80):\n print(packet.decode(\"UTF-8\"))\n```\n\nGives:\n\n```\nHTTP/1.1 301 Moved Permanently\nContent-length: 0\nLocation: https://python.org/\nConnection: close\n```\n\n### ```permutations(r=None)```\n\nReturns all possible permutations:\n\n```python\n>>> from pipe import permutations\n>>> for item in 'ABC' | permutations(2):\n... print(item)\n('A', 'B')\n('A', 'C')\n('B', 'A')\n('B', 'C')\n('C', 'A')\n('C', 'B')\n>>>\n```\n\n```python\n>>> for item in range(3) | permutations:\n... print(item)\n(0, 1, 2)\n(0, 2, 1)\n(1, 0, 2)\n(1, 2, 0)\n(2, 0, 1)\n(2, 1, 0)\n>>>\n```\n\n### `reverse`\n\nLike Python's built-in `reversed` function.\n\n```python\n>>> from pipe import reverse\n>>> list([1, 2, 3] | reverse)\n[3, 2, 1]\n>>>\n```\n\n### `select(fct)`\n\nAlias for `map(fct)`, see `map(fct)`.\n\n\n### `skip()`\n\nSkips the given quantity of elements from the given iterable, then yields\n\n```python\n>>> from pipe import skip\n>>> list((1, 2, 3, 4, 5) | skip(2))\n[3, 4, 5]\n>>>\n```\n\n\n### `skip_while(predicate)`\n\nLike itertools.dropwhile, skips elements of the given iterable\nwhile the predicate is true, then yields others:\n\n```python\n>>> from pipe import skip_while\n>>> list([1, 2, 3, 4] | skip_while(lambda x: x < 3))\n[3, 4]\n>>>\n```\n\n### `sort(key=None, reverse=False)`\n\nLike Python's built-in \"sorted\" primitive.\n\n```python\n>>> from pipe import sort\n>>> ''.join(\"python\" | sort)\n'hnopty'\n>>> [5, -4, 3, -2, 1] | sort(key=abs)\n[1, -2, 3, -4, 5]\n>>>\n```\n\n### `t`\n\nLike Haskell's operator \":\":\n\n```python\n>>> from pipe import t\n>>> for i in 0 | t(1) | t(2):\n... print(i)\n0\n1\n2\n>>>\n```\n\n### `tail(n)`\n\nYields the given quantity of the last elements of the given iterable.\n\n```python\n>>> from pipe import tail\n>>> for i in (1, 2, 3, 4, 5) | tail(3):\n... print(i)\n3\n4\n5\n>>>\n```\n\n### `take(n)`\n\nYields the given quantity of elements from the given iterable, like `head`\nin shell script.\n\n```python\n>>> from pipe import take\n>>> for i in count() | take(5):\n... print(i)\n0\n1\n2\n3\n4\n>>>\n```\n\n### `take_while(predicate)`\n\nLike `itertools.takewhile`, yields elements of the\ngiven iterable while the predicate is true:\n\n```python\n>>> from pipe import take_while\n>>> for i in count() | take_while(lambda x: x ** 2 < 100):\n... print(i)\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n>>>\n```\n\n### `tee`\n\ntee outputs to the standard output and yield unchanged items, useful for\ndebugging a pipe stage by stage:\n\n```python\n>>> from pipe import tee\n>>> sum([\"1\", \"2\", \"3\", \"4\", \"5\"] | tee | map(int) | tee)\n'1'\n1\n'2'\n2\n'3'\n3\n'4'\n4\n'5'\n5\n15\n>>>\n```\n\nThe `15` at the end is the `sum` returning.\n\n\n### `transpose()`\n\nTransposes the rows and columns of a matrix.\n\n```python\n>>> from pipe import transpose\n>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | transpose\n[(1, 4, 7), (2, 5, 8), (3, 6, 9)]\n>>>\n```\n\n### `traverse`\n\nRecursively unfold iterables:\n\n```python\n>>> list([[1, 2], [[[3], [[4]]], [5]]] | traverse)\n[1, 2, 3, 4, 5]\n>>> squares = (i * i for i in range(3))\n>>> list([[0, 1, 2], squares] | traverse)\n[0, 1, 2, 0, 1, 4]\n>>>\n```\n\n### `uniq(key=None)`\n\n\nLike dedup() but only deduplicate consecutive values, using the given\n`key` function if provided (or else the identity).\n\n```python\n>>> from pipe import uniq\n>>> list([1, 1, 2, 2, 3, 3, 1, 2, 3] | uniq)\n[1, 2, 3, 1, 2, 3]\n>>> list([1, -1, 1, 2, -2, 2, 3, 3, 1, 2, 3] | uniq(key=abs))\n[1, 2, 3, 1, 2, 3]\n>>>\n```\n\n### `where(predicate)`, `filter(predicate)`\n\nOnly yields the matching items of the given iterable:\n\n```python\n>>> list([1, 2, 3] | where(lambda x: x % 2 == 0))\n[2]\n>>>\n```\n\nDon't forget they can be aliased:\n\n```python\n>>> positive = where(lambda x: x > 0)\n>>> negative = where(lambda x: x < 0)\n>>> sum([-10, -5, 0, 5, 10] | positive)\n15\n>>> sum([-10, -5, 0, 5, 10] | negative)\n-15\n>>>\n```\n\n## Constructing your own\n\nYou can construct your pipes using the `Pipe` class like:\n\n```python\nfrom pipe import Pipe\nsquare = Pipe(lambda iterable: (x ** 2 for x in iterable))\nmap = Pipe(lambda iterable, fct: builtins.map(fct, iterable)\n>>>\n```\n\nAs you can see it's often very short to write, and with a bit of luck\nthe function you're wrapping already takes an iterable as the first\nargument, making the wrapping straight forward:\n\n```python\n>>> from collections import deque\n>>> from pipe import Pipe\n>>> end = Pipe(deque)\n>>>\n```\n\nand that's it `itrable | end(3)` is `deque(iterable, 3)`:\n\n```python\n>>> list(range(100) | end(3))\n[97, 98, 99]\n>>>\n```\n\nIn case it gets more complicated one can use `Pipe` as a decorator to\na function taking an iterable as the first argument, and any other\noptional arguments after:\n\n```python\n>>> from statistics import mean\n\n>>> @Pipe\n... def running_average(iterable, width):\n... items = deque(maxlen=width)\n... for item in iterable:\n... items.append(item)\n... yield mean(items)\n\n>>> list(range(20) | running_average(width=2))\n[0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5]\n>>> list(range(20) | running_average(width=10))\n[0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5]\n>>>\n```\n\n\n## One-off pipes\n\nSometimes you just want a one-liner, when creating a pipe you can specify the function's positional and named arguments directly\n\n```python\n>>> from itertools import combinations\n\n>>> list(range(5) | Pipe(combinations, 2))\n[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n>>>\n```\n\na simple running sum with initial starting value\n\n```python\n>>> from itertools import accumulate\n\n>>> list(range(10) | Pipe(accumulate, initial=1))\n[1, 1, 2, 4, 7, 11, 16, 22, 29, 37, 46]\n>>>\n```\n\nor filter your data based on some criteria\n\n```python\n>>> from itertools import compress\n\nlist(range(20) | Pipe(compress, selectors=[1, 0] * 10))\n[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n>>> list(range(20) | Pipe(compress, selectors=[0, 1] * 10))\n[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]\n>>>\n```\n\n## Euler project samples\n\n> Find the sum of all the multiples of 3 or 5 below 1000.\n\n```python\n>>> sum(count() | where(lambda x: x % 3 == 0 or x % 5 == 0) | take_while(lambda x: x < 1000))\n233168\n>>>\n```\n\n> Find the sum of all the even-valued terms in Fibonacci which do not\n> exceed four million.\n\n```python\nsum(fib() | where(lambda x: x % 2 == 0) | take_while(lambda x: x < 4000000))\n```\n\n> Find the difference between the sum of the squares of the first one\n> hundred natural numbers and the square of the sum.\n\n```python\n>>> square = map(lambda x: x ** 2)\n>>> sum(range(101)) ** 2 - sum(range(101) | square)\n25164150\n>>>\n```\n\n\n# Going deeper\n## Partial Pipes\n\nA `pipe` can be parametrized without being evaluated:\n\n```python\n>>> running_average_of_two = running_average(2)\n>>> list(range(20) | running_average_of_two)\n[0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5]\n>>>\n```\n\nFor multi-argument pipes then can be partially initialized, you can think of curying:\n\n```python\nsome_iterable | some_pipe(1, 2, 3)\nsome_iterable | Pipe(some_func, 1, 2, 3)\n```\n\nis strictly equivalent to:\n\n```python\nsome_iterable | some_pipe(1)(2)(3)\n```\n\nSo it can be used to specialize pipes, first a dummy example:\n\n```python\n>>> @Pipe\n... def addmul(iterable, to_add, to_mul):\n... \"\"\"Computes (x + to_add) * to_mul to every items of the input.\"\"\"\n... for i in iterable:\n... yield (i + to_add) * to_mul\n\n>>> mul = addmul(0) # This partially initialize addmul with to_add=0\n>>> list(range(10) | mul(10))\n[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]\n\n```\n\nWhich also works with keyword arguments:\n\n```python\n>>> add = addmul(to_mul=1) # This partially initialize addmul with `to_mul=1`\n>>> list(range(10) | add(10))\n[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n>>>\n```\n\n\nBut now for something interesting:\n\n```python\n>>> import re\n>>> @Pipe\n... def grep(iterable, pattern, flags=0):\n... for line in iterable:\n... if re.match(pattern, line, flags=flags):\n... yield line\n...\n>>> lines = [\"Hello\", \"hello\", \"World\", \"world\"]\n>>> for line in lines | grep(\"H\"):\n... print(line)\nHello\n>>>\n```\n\nNow let's reuse it in two ways, first with a pattern:\n\n```python\n>>> lowercase_only = grep(\"[a-z]+$\")\n>>> for line in lines | lowercase_only:\n... print(line)\nhello\nworld\n>>>\n```\n\nOr now with a flag:\n\n```python\n>>> igrep = grep(flags=re.IGNORECASE)\n>>> for line in lines | igrep(\"hello\"):\n... print(line)\n...\nHello\nhello\n>>>\n```\n\n\n## Lazy evaluation\n\nPipe uses generators all the way down, so it is naturally lazy.\n\nIn the following examples we'll use\n[itertools.count](https://docs.python.org/fr/3/library/itertools.html#itertools.count):\nan infinite generator of integers.\n\nWe'll make use of the `tee` pipe too, which prints every values that\npasse through it.\n\nThe following example does nothing, nothing is printed by `tee` so no\nvalue passed through it. It's nice because generating an infinite\nsequence of squares is \"slow\".\n\n```python\n>>> result = count() | tee | select(lambda x: x ** 2)\n>>>\n```\n\nChaining more pipes still won't make previous ones start generating\nvalues, in the following example not a single value is pulled out of\n`count`:\n\n```python\n>>> result = count() | tee | select(lambda x: x ** 2)\n>>> first_results = result | take(10)\n>>> only_odd_ones = first_results | where(lambda x: x % 2)\n>>>\n```\n\nSame without variables:\n\n```python\n>>> result = (count() | tee\n... | select(lambda x: x ** 2)\n... | take(10)\n... | where(lambda x: x % 2))\n>>>\n```\n\n\nOnly when values are actually needed, the generators starts to work.\n\nIn the following example only two values will be extracted out of `count`:\n- `0` which is squared (to `0`), passes the `take(10)` eaily,\n but is dropped by `where`\n- `1` which is squared (to `1`), also easily passes the `take(10)`,\n passes the `where`, and passes the `take(1)`.\n\nAt this point `take(1)` is satisfied so no other computations need to\nbe done. Notice `tee` printing `0` and `1` passing through it:\n\n```python\n>>> result = (count() | tee\n... | select(lambda x: x ** 2)\n... | take(10)\n... | where(lambda x: x % 2))\n>>> print(list(result | take(1)))\n0\n1\n[1]\n>>>\n```\n\n## Deprecations\n\nIn pipe 1.x a lot of functions were returning iterables and a lot\nother functions were returning non-iterables, causing confusion. The\none returning non-iterables could only be used as the last function of\na pipe expression, so they are in fact useless:\n\n```python\nrange(100) | where(lambda x: x % 2 == 0) | add\n```\n\ncan be rewritten with no less readability as:\n\n```python\nsum(range(100) | where(lambda x: x % 2 == 0))\n```\n\nso all pipes returning non-iterables were deprecated (raising\nwarnings), and finally removed in pipe 2.0.\n\n\n## What should I do?\n\nOh, you just upgraded pipe, got an exception, and landed here? You\nhave three solutions:\n\n\n1) Stop using closing-pipes, replace `...|...|...|...|as_list` to\n `list(...|...|...|)`, that's it, it's even shorter.\n\n2) If \"closing pipes\" are not an issue for you, and you really like\n them, just reimplement the few you really need, it often take a very\n few lines of code, or copy them from\n [here](https://github.com/JulienPalard/Pipe/blob/dd179c8ff0aa28ee0524f3247e5cb1c51347cba6/pipe.py).\n\n3) If you still rely on a lot of them and are in a hurry, just `pip install pipe<2`.\n\n\nAnd start testing your project using the [Python Development\nMode](https://docs.python.org/3/library/devmode.html) so you catch\nthose warnings before they bite you.\n\n\n## But I like them, pleassssse, reintroduce them!\n\nThis has already been discussed in [#74](https://github.com/JulienPalard/Pipe/issues/74).\n\nAn `@Pipe` is often easily implemented in a 1 to 3 lines of code\nfunction, and the `pipe` module does not aim at giving all\npossibilities, it aims at giving the `Pipe` decorator.\n\nSo if you need more pipes, closing pipes, weird pipes, you-name-it,\nfeel free to implement them on your project, and consider the\nalready-implemented ones as examples on how to do it.\n\nSee the `Constructing your own` paragraph below.\n",
"bugtrack_url": null,
"license": "MIT License",
"summary": "Module enabling a sh like infix syntax (using pipes)",
"version": "2.2",
"project_urls": {
"repository": "https://github.com/JulienPalard/Pipe"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "1f2196f1508f67fadb4ab7e5df7c3389e4a2f03cba92f62846f99f6301cf0735",
"md5": "1ff3fa26dab821921eb72c1078d026ec",
"sha256": "0a5c3202ff35122f69a34ccbd40c9658646f033cc941055304fe8bfa7e13376e"
},
"downloads": -1,
"filename": "pipe-2.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "1ff3fa26dab821921eb72c1078d026ec",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 9655,
"upload_time": "2024-04-04T06:37:16",
"upload_time_iso_8601": "2024-04-04T06:37:16.383111Z",
"url": "https://files.pythonhosted.org/packages/1f/21/96f1508f67fadb4ab7e5df7c3389e4a2f03cba92f62846f99f6301cf0735/pipe-2.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "5337aef2cba01787ad8bd266705a95c23db0e9d0b7cd0e01582c969143892655",
"md5": "bfe272e979668677317e7ee16f08aa54",
"sha256": "6a253198e3bc542ffaf0a4222376586bce8583b27a9ddbc2cfbaa554c049230d"
},
"downloads": -1,
"filename": "pipe-2.2.tar.gz",
"has_sig": false,
"md5_digest": "bfe272e979668677317e7ee16f08aa54",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 10456,
"upload_time": "2024-04-04T06:37:17",
"upload_time_iso_8601": "2024-04-04T06:37:17.686399Z",
"url": "https://files.pythonhosted.org/packages/53/37/aef2cba01787ad8bd266705a95c23db0e9d0b7cd0e01582c969143892655/pipe-2.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-04-04 06:37:17",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "JulienPalard",
"github_project": "Pipe",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "pipe"
}