[Python-3000] Iterators for dict keys, values, and items == annoying :)

Paul Moore p.f.moore at gmail.com
Tue Mar 28 10:45:34 CEST 2006


On 3/28/06, adam deprince <adam.deprince at gmail.com> wrote:
> > I won't go on any more - you probably get the idea...
>
> Agreed, scratch that, I'll rework it in the spriit of views.

Thanks for taking my comments so well! When I wrote them, I was
*really* worried they came across as too negative.

The key here (in my view) is probably to think in terms of use
patterns. In a for loop

    for k in d: # or d.keys()
    for v in d.values():
    for k, v in d.items():

you have no access to anything other than the return values from
next(). So, extending the methods on the iterator is effectively
useless.

If you pass around the iterator, you're going to be passing it to a
function (for in-line code, you will definitely have access to the
underlying container, so there's no value to going via the iterator).

OK, so we're looking specifically at functions, which have access to
the iterator only, and not to the underlying object. That's the key
use case. So, we need to document the function's requirements. That's
why we need a named protocol, and not just "an iterator which also
supports methods X, Y and Z", because otherwise we end up with yet
another "file-like object" mess.

There are *lots* of concepts that might help people write functions
like this. Just off the top of my head (excuse my lousy naming):

 - bounded iterator (supports a length method, guaranteed non-infinite)
 - reiterator (supports clone/restart type operations)
 - mutable iterator (supports delete and insert, with appropriate guarantees)

It's only really use cases that can identify which of these might be
worth supporting.

Hope this helps,
Paul.


More information about the Python-3000 mailing list