beginning index for generators

Diez B. Roggisch deetsNOSPAM at web.de
Sat Oct 16 15:50:39 CEST 2004


kosh wrote:

> I was wondering if there is or there could be some way to pass a generator
> an optional starting index so that if it supported that slicing could be
> made more efficient. Right now if you do use a generator and do a
> [100:110] or any other kind of slice it reads all the values up to 100
> also.

<snip>
> I have no idea how feasible this is, what it would take to implement it
> etc but I did not get any matches searching this on google and wanted to
> throw it out here to see if others have run into situations in which this
> would be very useful also and would further simplify code and make it more
> readable.


There is no way of doing this implicit - only explicit, with deep knowledge
of what actually gets iterated over by the generator - and as the slicing
is a second, independent operation on the generator that only knows about
the generator implementing the iterable protocol, it can't jump to
arbitrary positions in that generator. And as you said before, the
generator needs to be invoked that 100 times so it has consistent internal
state.

> 
> I would also love to know of other ways that this problem could be solved
> but I would like it to be as transparent as possible to existing calling
> code.

Maybe imlementing __getslice__ on your container object helps - that way,
calling code has not to be changed, but the implementation can take
advantage from the underlying collection beeing efficiently sliceable.



-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list