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

Guido van Rossum guido at python.org
Sat Mar 25 03:58:22 CET 2006


On 3/24/06, Tim Peters <tim.peters at gmail.com> wrote:
> [Guido]
> > The Java collections framework actually has an API and an idiom that
> > make this work: therd's a method on the *iterator* that deletes the
> > current item without disturbing the iteration.
>
> Yup, I saw that:
>
>     http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html
>
> It's at least curious that there isn't also a method to add an item in
> the base Iterator interface.

I could ask my drinking buddy Josh Bloch, but I'll try to channel him
first: (a) the use case isn't as attractive (why would you want to
insert an item during an iteration? the use case for deletion during
iteration is very natural); (b) did you mean to insert it before,
after, or a random item? for hash sets that doesn't matter, but for
trees and lists it does. (c) it would be hard to implement for hash
sets because you may not have a choice about not rehashing.

[...]
> > Note that this is all quite independent from the views proposal (also
> > inspired by Java).
>
> I'm not sure I saw a coherent "views proposal" ;-)  Java has some nice
> ideas, but I'd think it's too elaborate for your tastes (and, by
> extension, for Python's).  For example, it has six(?) collection
> interfaces, two of which don't even extend the base Collection
> interface.  AFAICT, what Java calls "views" are unique to some methods
> of its Map and SortedMap interfaces.

Right, the views only make sense for maps that have separate keys and values.

> To be concrete, is what you're calling "a view" the kind of thing
> returned by Java's AbstsactMap.entrySet()?:
>
>     http://java.sun.com/j2se/1.4.2/docs/api/java/util/AbstractMap.html

Yes. Another example is Map.keySet(), which returns a set view of the
keys of a map:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html#keySet()

> That's closest to Python's items(), and AbstractMap.keys() is closest
> to Python's keys().  Java being Java, AbstractMap.values() returns a
> different _type_ of object than those two (Java's further
> sub-distinction between "set views" and "collection views").

The "Abstract" classes aren't the most interesting pieces; they are
really building blocks for implementers, as explained here:

http://java.sun.com/j2se/1.4.2/docs/guide/collections/overview.html
(section "Collection Implementations", last para of the intro).

The really core stuff is in the interfaces.

The difference between sets and collections is that collections may
have duplicates; that's pretty essential for the thing you get from
values(), but keys() and items() return sets (of different types).

> I vote to steal the good parts and drop all the distinctions :-)

Maybe. I need a volunteer to write the PEP!

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list