Sequence iterators with __index__

Matimus mccredie at gmail.com
Wed Jun 25 17:35:00 CEST 2008


On Jun 24, 4:19 pm, schickb <schi... at gmail.com> wrote:
> On Jun 24, 3:45 pm, Matimus <mccre... at gmail.com> wrote:
>
>
>
> > > I think it would be useful if iterators on sequences had the __index__
> > > method so that they could be used to slice sequences. I was writing a
> > > class and wanted to return a list iterator to callers.  I then wanted
> > > to let callers slice from an iterator's position, but that isn't
> > > supported without creating a custom iterator class.
>
> > Could you post an example of what you are talking about? I'm not
> > getting it.
>
> Interactive mock-up:
>
> >>> a = ['x','y','z']
> >>> it = iter(a)
> >>> a[it:]
> ['x', 'y', 'z']
> >>> it.next()
> 'x'
> >>> a[it:]
> ['y', 'z']
> >>> a[:it]
> ['x']
> >>> it.next()
> 'y'
> >>> a[it:]
>
> ['z']
>
> This lets you use sequence iterators more general position indicators.
> Currently if you want to track a position and slice from a tracked
> position you must do it manually with an integer index. It's not
> difficult, but given that sequence iterators already do that already
> it seems redundant (and of course more error prone).
>
> > In any case, the first step is writing a PEP.http://www.python.org/dev/peps/
>
> Ok thanks, but I do want some idea of interest level before spending a
> bunch of time on this.
>
> -Brad

I have no problem with being able to query the position (state) of an
iterator without changing its state. I think using the iterator itself
as the index or part of a slice in the original sequence is non-
obvious and also less useful than just a new method to query state.
"Explicit is better than Implicit". I would rather see just
`it.index()` or `it.state()` than the new specialized behavior implied
by `it.__index__()`. I'm leaning towards `state` because sequences
already have an `index` method, and two methods of the same name with
different behaviors may be confusing. This gives you essentially the
same ability, and the code seems a little more obvious IMHO.

>>> a = ['x','y','z']
>>> it = iter(a)
>>> a[it.state():]
['x', 'y', 'z']
>>> it.next()
'x'
>>> a[it.state():]
['y', 'z']
>>> a[:it.state()]
['x']
>>> it.next()
'y'
>>> a[it.state():]
['z']
>>> it.state()
2


Matt



More information about the Python-list mailing list