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

Guido van Rossum guido at python.org
Fri Mar 24 05:25:33 CET 2006


On 3/23/06, Delaney, Timothy (Tim) <tdelaney at avaya.com> wrote:
> This whole discussion suggests to me that what would be best is if we
> defined an actual "view" protocol, and various builtins return views,
> rather than either copies or iterators.

Right.

> A view provides the same access methods, etc as the object it is backed
> by.

No it doesn't! Otherwise there would be no difference between a view
and the underlying object. Please read the Java docs that I referenced
before.

> The aim of a view is to be lightweight. A view should not allow
> modification of the underlying object, but the view itself may change if
> the underlying object changes (and how it changes would need to be
> documented).

The Java collections framework has precise rules for this. Please read
it. A better URL to start than the one I gave before is:

http://java.sun.com/j2se/1.4.2/docs/guide/collections/index.html

For eqample, here's a quote from the spec for Map.keySet() -- the Java
equivalent of dict.keys()  -- at
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html#keySet():

"""
Returns a set view of the keys contained in this map. The set is
backed by the map, so changes to the map are reflected in the set, and
vice-versa. If the map is modified while an iteration over the set is
in progress, the results of the iteration are undefined. The set
supports element removal, which removes the corresponding mapping from
the map, via the Iterator.remove, Set.remove, removeAll retainAll, and
clear operations. It does not support the add or addAll operations.
"""

> For the case of dict.keys(), a list-view would be returned.

No, a set view. You know that the keys are unique so it is a set; and
a list view would imply cheap random access, which does not work for a
hash table -- it's expensive to compute the N'th element of a hash
table with holes, since the only way to do it is to start at the
beginning and count forward, skipping the holes, until you've passed
the requested number of non-holes.

> From all
> appearances, this would be an immutable sequence i.e. it would implement
> __getitem__, __iter__ and __len__.

 No. See the Java quote above.

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


More information about the Python-3000 mailing list