Sequence iterators with __index__

schickb schickb at gmail.com
Wed Jun 25 10:16:22 CEST 2008


On Jun 25, 12:11 am, schickb <schi... at gmail.com> wrote:
>
> But this isn't just about slicing. I'd like sequence iterators to be
> usable as simple indexes as well; like a[it] (which __index__ would
> also provide).

It occurred to me that this wouldn't need to be limited to sequence
iterators. Although somewhat of a misnomer, __index__ could just a
well return the current key for mapping iterators. Type checking would
then be specific to the context, rather than hard-coded to integer.
Perhaps __position__ would have been a better name.

The generalized idea here is that iterators identify positions in
collections, so why shouldn't they be usable where collections accept
such identifiers?

>>> m = {'a':1, 'b':2}
>>> it = iter(m)
>>> m[it]
1
>>> it.next()
>>> m[it]
2

These are trivial examples, but there are lots of uses for abstract
position indicators. From what I've seen, iterators are currently used
almost exclusively as temporary objects in loops. But perhaps if they
had a bit more functionality they could serve a wider purpose.

-Brad



More information about the Python-list mailing list