Bash-like pipes in Python

Steven D'Aprano steve at pearwood.info
Thu Mar 17 10:10:45 EDT 2016


On Thu, 17 Mar 2016 04:04 am, Marko Rauhamaa wrote:

> Steven D'Aprano <steve at pearwood.info>:
> 
>> 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/
> 
> Nice. The other day we talked about Python replacing bash. Pipelining is
> a big step in that direction.
> 
> Note also the Scheme Shell (scsh):
> URL: https://scsh.net/docu/html/man-Z-H-3.html>.
> 
> Question: Could the generators define __repr__ so you wouldn't need to
> terminate the pipeline with "List" in interactive use?


Short answer: no.

Long answer: well, technically it could be possible, but not the way it is
written at the moment.

At the moment, the data being processed by the Map, Filter, etc. are
ordinary lists or iterators. In order to give them a customer __repr__, I
would have to change the Map and Filter __ror__ method to return some
custom type which behaves as an iterable but has the appropriate __repr__.
I don't want to do that: I want the pipeline functions to return ordinary
lists or iterators, whichever is appropriate.

There's also the problem that __repr__ shouldn't mutate an object. Suppose
we did give iterators a __repr__ that displays their content. That would
exhaust the iterator, and you would have something like this:


it = iter([1, 2, 3])
repr(it)
=> prints "[1; 2; 3]"
repr(it)  # iterator is now exhausted
=> prints "[]"


I don't think this is a good idea.


-- 
Steven




More information about the Python-list mailing list