How about adding slice notation to iterators/generators?

Carl Banks pavlovevidence at gmail.com
Sun Oct 18 19:51:26 EDT 2009


On Oct 18, 2:53 pm, Eloff <dan.el... at gmail.com> wrote:
> On Oct 16, 7:38 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
>
> > You would burden everyone who writes a custom iterator to provide a
> > __getitem__ method just because you're too lazy to type out the word
> > islice?
>
> No, of course not. That would be stupid. Custom iterators are
> iterators, so they would also get the default __getitem__ which would
> work just perfectly for them.


Ok, here's a simple (Python 2.x) custom iterator.

class Alphabet(object):
    def __init__(self):
        self.c = 65
    def __iter__(self):
        return self
    def next(self):
        if self.c > 90:
            raise StopIteration
        letter = chr(self.c)
        self.c += 1
        return letter


Let's see what happens *currently* in Python when you try to apply
slice indexing.

for x in AB()[4:9]:  # loop through letters 4 through 8
    print x


This, as expected, raises a type error:

TypeError: 'AB' object is unsubscriptable


Now, let's try to modify Python to fix this.  All we have to do is to
define __getitem__ for the default iterator, so let's define it in the
common iterator type, which is....

Hm, wait a second, problem here.  The simple iterator I defined above
isn't an instance of any common iterator type.  In fact there is no
common iterator type.

You see, iterator is a *protocol*.  An object is not an iterator by
virtue of being an instance of an iterator type, it's an iterator
because it supports a protocol.  In fact that protocol is extremely
simple: all an iterator has to do is define __iter__() to return self,
define next() to return next item, and raise StopIteration when it's
done.

So you see, to support slice syntax one would indeed burden all custom
iterators to implement __getitem__ method, which would arguably
increase the implementor's burden by 30%.


> If they needed to override it, they
> could. Remember, my proposal was to add a default __getitem__ for
> iterators that is really just islice.

There is no default __getitem__ for iterators so this proposal won't
work.


Carl Banks



More information about the Python-list mailing list