Bash-like pipes in Python

Omar Abou Mrad omar.aboumrad at gmail.com
Wed Mar 16 11:22:39 EDT 2016


On Wed, Mar 16, 2016 at 4:57 PM, 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
>
> <..snip..>
>

Would be nice if this was possible:

>>> get_digits = Filter(str.isdigit) | Map(int)
>>> 'kjkjsdf399834' | get_digits

Also, how about using '>>' instead of '|' for "Forward chaining"

Regards,

Omar



More information about the Python-list mailing list