itertools candidate: warehouse()

Peter Otten __peter__ at web.de
Tue Oct 19 14:31:23 EDT 2004


Robert Brewer wrote:

>>iavailable = chain(stock, starmap(random.random, repeat(())))
> 
> Ah, thanks! The docs don't really make it clear that you can pass a
> callable to repeat() and have it be called on each iteration. The Python
> "equivalent" given in the docs looks like you get the same static object
> every time... :/

No, you cannot pass a callable to repeat() and have it called. In the above
line repeat(()) yields the same empty tuple ad infinitum. The trick is that
starmap() calls random.random() with that empty tuple as the argument list,
which looks a little silly when you write it explicitly as
random.random(*()).

In total, the equivalent

def gen_available(stock):
    for item in stock:
        yield item
    while True:
        yield random.random()

iavailable = gen_available(stock)

has less potential of puzzling the unsuspecting reader who, as the saying
goes, may be you in a few months.

Peter





More information about the Python-list mailing list