How about adding slice notation to iterators/generators?
rylesny at gmail.com
Sat Oct 17 02:29:47 CEST 2009
On Oct 16, 5:28 pm, Eloff <dan.el... at gmail.com> wrote:
> By giving iterators a default, overridable, __getitem__ that is just
> syntactic sugar for islice, they would share a slightly larger
> interface subset with the builtin container types. In a duck-typed
> language like python, that's almost always a good thing. You could use
> iterators in more situations which expect something more like a list.
> As long as it breaks no rationally existing code, I can think of no
> good reason why not to do this in a future python.
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:
a == a
a[1:4] == a[1:4]
If you saw the above code would you want to think twice above whether
or not these expressions were true?
Iterators don't have a general concept of "get item" like types such
as strings, lists, etc. They have a concept of "get next item". So,
with your proposal, i != i and i[1:4] != i[1:4].
Not only that, it's also common for types with __getitem__ to have
__len__, which we obviously can't provide.
So, ultimately, although it could afford some small conveniences, I
think trying to mix iterators with __getitem__ would cause too much
The use of islice() is both readable and explicit. It's very clear to
the reader that you're working with iterators and that items will be
consumed (something that's not reversible).
More information about the Python-list