Bash-like pipes in Python

Stefan Otte stefan.otte at gmail.com
Wed Mar 16 11:38:49 EDT 2016


I wrote this little lib "pelper" [0] which has the elixir inspired
pipe [1]. I initially had an implementation that used operator
overloading but found that the "|" syntax was not really necessary. I
just use the function `pipe` [2]

Some examples from the repo:

``pipe`` allows you to turn something which is hard to read:
>>> from math import ceil, sqrt
>>> sqrt(pow(int(ceil(float("2.1"))), 2))
3.0
into something that is easy to read:
>>> pipe("2.1", float, ceil, int, lambda x: x*x, sqrt)
3.0

>>> pipe("atababsatsatsastatbadstssdhhhnbb", set, (sorted, {"reverse": True}))
['t', 's', 'n', 'h', 'd', 'b', 'a']



Cheers,
 Stefan


[0] https://github.com/sotte/pelpe
[1] http://elixir-lang.org/getting-started/enumerables-and-streams.html#the-pipe-operator
[2] https://github.com/sotte/pelper/blob/master/pelper/pelper.py#L14
Beste Grüße,
 Stefan



On Wed, Mar 16, 2016 at 4:29 PM, Random832 <random832 at fastmail.com> wrote:
> On Wed, Mar 16, 2016, at 11:20, Random832 wrote:
>> How about:
>>
>> from functools import partial, reduce
>> from operator import mul
>> def rcall(arg, func): return func(arg)
>> def fpipe(*args): return reduce(rcall, args)
>
> It occurs to me that this suggests a further refinement: have all
> functions (and classes? map and filter seem to be classes.) define
> __ror__ as calling the left-hand operand. Then this could be written as
> "abcd12345xyz" | pfilter(str.isdigit) | pmap(int) | preduce(mul).
>
> You could also define, say, __mul__ as partial application, so you could
> write "abcd12345xyz" | filter*str.isdigit | map*int | reduce*mul.
>
>> pfilter = partial(partial, filter)
>> pmap = partial(partial, map)
>> preduce = partial(partial, reduce)
>>
>> fpipe("abcd12345xyz", pfilter(str.isdigit), pmap(int), preduce(mul))
> --
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list