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

Delaney, Timothy (Tim) tdelaney at avaya.com
Fri Mar 24 03:15:00 CET 2006


Jeremy Hylton wrote:

> On 3/23/06, Ian Bicking <ianb at colorstudy.com> wrote:
>> One idea I had after reading a post of Brett's was a dual-use
>> attribute; if you do d.keys you get an iterable (not an iterator, of
>> course), and if you call that iterable you get a list.  This is
>> backward compatible, arguably prettier anyway to make it a property
>> (since there's no side effects and getting an iterable isn't
>> expensive, the method call seems somewhat superfluous).
> 
> I don't think we should overload attributes name such that they are
> sometimes attributes and sometimes methods, particularly when they
> return things that behave almost-but-not-quite the same.  It will
> create confusion and subtle bugs.

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.

A view provides the same access methods, etc as the object it is backed
by. 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).

For the case of dict.keys(), a list-view would be returned. From all
appearances, this would be an immutable sequence i.e. it would implement
__getitem__, __iter__ and __len__.

Tim Delaney


More information about the Python-3000 mailing list