How about adding slice notation to iterators/generators?

Eloff dan.eloff at gmail.com
Sun Oct 18 17:53:20 EDT 2009


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. If they needed to override it, they
could. Remember, my proposal was to add a default __getitem__ for
iterators that is really just islice.

Ryles makes a good point though:

>I think Python programmers have learned to expect certain things from
>objects that support __getitem__. For example, indexing and slicing is
>repeatable on the same object:

That indexing/slicing iterators is not repeatable is likely to negate
much of the advantage of supporting a larger interface (because it
would be supported inconsistently, passing an iterator to something
that expects __getitem__ could be surprising.)

That does not mean it has no value in working with iterators, it
offers the same value islice does, just more conveniently.

Steven:
>If you want to support slicing, go right ahead, but please, I beg you,
>don't force me to support it in my iterators!

As I said to Carl Banks, forcing you do something differently is not
my aim here. Your other points apply equally to islice, which already
exists, and do not invalidate its purpose.

The main use case I'm thinking about here is skipping elements or
limiting results from iterators, usually in for loops:

for x in my_iter[5:]:
    ...

for x in my_iter[:5]:
    ...

Clearly that's easier and more readable than using islice. Nobody has
yet to provide a concrete reason why that would be a _bad thing_. That
doesn't make it a _good thing_, either.

-Dan



More information about the Python-list mailing list