Bash-like pipes in Python

Joel Goldstick joel.goldstick at gmail.com
Wed Mar 16 11:09:04 EDT 2016


On Wed, Mar 16, 2016 at 10:57 AM, Steven D'Aprano <steve at pearwood.info>
wrote:

> There's a powerful technique used in shell-scripting languages like bash:
> pipes. The output of one function is piped in to become the input to the
> next function.
>
> According to Martin Fowler, this was also used extensively in Smalltalk:
>
> http://martinfowler.com/articles/collection-pipeline/
>
> and can also be done in Ruby, using method chaining.
>
> Here is a way to do functional-programming-like pipelines to collect and
> transform values from an iterable:
>
> https://code.activestate.com/recipes/580625-collection-pipeline-in-python/
>
> For instance, we can take a string, extract all the digits, convert them to
> ints, and finally multiply the digits to give a final result:
>
> py> from operator import mul
> py> "abcd12345xyz" | Filter(str.isdigit) | Map(int) | Reduce(mul)
> 120
>
>
> (For the definitions of Filter, Map and Reduce, see the code at the
> ActiveState recipe, linked above). In my opinion, this is much nicer
> looking that the standard Python `filter`, `map` and `reduce`:
>
> py> reduce(mul, map(int, filter(str.isdigit, "abcd12345xyz")))
> 120
>
> as this requires the operations to be written in the opposite order to the
> order that they are applied.
>
>
> This is interesting, but the part I'm missing is the use of the Pipe
symbol '|' in python.  Can you elaborate

>
> --
> Steven
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Joel Goldstick
http://joelgoldstick.com/ <http://joelgoldstick.com/stats/birthdays>
http://cc-baseballstats.info/



More information about the Python-list mailing list