Bash-like pipes in Python

Chris Angelico rosuav at gmail.com
Thu Mar 17 10:36:38 EDT 2016


On Fri, Mar 18, 2016 at 1:10 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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.

They don't have to be iterators, just iterables, right? They could
return a one of these:

class QuantumList:
    def __init__(self, iterable):
        self.iter = iter(iterable)
        self.list = []
    def __iter__(self):
        yield from self.list
        while "moar stuff":
            try: val = next(self.iter)
            except StopIteration: return
            self.list.append(val)
            yield val
    def __repr__(self):
        self.list.extend(self.iter)
        return repr(self.list)

This object has a generator/list duality, but if you observe it, it
collapses to a list. When used interactively, it'd be pretty much the
same as calling list() as the last step, but in a script, they'd
operate lazily.

Quantum computing is here already!

ChrisA



More information about the Python-list mailing list