[Python-ideas] Batching/grouping function for itertools

Ron Adam ron3200 at gmail.com
Sun Dec 8 16:40:27 CET 2013



On 12/08/2013 09:22 AM, Chris Angelico wrote:
>> >How about 2 lower level building blocks that would make these things easier
>> >to make and think about.
>> >
>> >
>> >Possibly function to take the next n items of an iterator without advancing
>> >it.
> Fundamentally impossible.

In some cases yes, but you would know if it could work before you chose to 
use these.

 > Here's a function that returns an iterator:
>
> def d20():
>      import random
>      while True:
>          yield random.randrange(1,21)
>
> dice_roller = d20()
>
> How are you going to take the next n items from dice_roller without
> advancing it?

If it is to work with generators too...

The function would need to be a wrapper that keeps a buffer.  And the front 
of the buffer would always be the next to be yielded if there is anything 
in it.

In the case of advancing an generator, without taking the values, it would 
still need to call the __next__ methods on it, but not actually return the 
values.

Yes, it won't be as simple as it sounds. ;-)

cheers,
    Ron













More information about the Python-ideas mailing list