[Python-ideas] Use the plus operator to concatenate iterators

Steven D'Aprano steve at pearwood.info
Wed Aug 5 05:01:47 CEST 2015


On Tue, Aug 04, 2015 at 10:37:00PM -0400, random832 at fastmail.us wrote:

> Suppose iterator * number returns a new iterator which will iterate
> through the original iterator once, caching the results, and then yield
> the cached results n-1 times.

Repetition on an arbitrary iterator is ambiguous. If I say, "repeat the 
list [1,2,3] twice" there is no ambiguity, I must get [1, 2, 3, 1, 2, 3] 
or there is some problem. But iterators can have non-deterministic 
lengths and values:

def gen():
    while random.random() < 0.9:
        yield random.random()

What does it mean to "repeat gen twice"? It might mean either of:

- generate one run of values using gen, then repeat those same values;

- generate two runs of values using gen.

Both are easy to write, e.g.:

list(gen())*2  # explicitly cache the values, then repeat

chain(gen(), gen())  # explicitly use two separate runs

In the face of ambiguity, resist the temptation to guess. There's no 
obvious right behaviour here, whichever you bake into iterator * you 
will make about half the users unhappy because it doesn't support their 
use-case.

Not every simple expression needs to be an operator.



-- 
Steve


More information about the Python-ideas mailing list