dict.keys() ?

George Sakkis george.sakkis at gmail.com
Sat Jan 27 01:18:20 EST 2007


On Jan 26, 10:04 pm, bearophileH... at lycos.com wrote:

> The PEP 3100:http://www.python.org/dev/peps/pep-3100/
> says:
>
> Return iterators instead of lists where appropriate for atomic type
> methods (e.g. dict.keys(), dict.values(), dict.items(), etc.); iter*
> methods will be removed. Better: make keys(), etc. return views ala
> Java collections???
> ...
> To be removed:
>    dict.setdefault()? [15]
>    dict.has_key() method [done]
>
> I may be sleepy now, but maybe the keys() method too can be removed;
> otherwise the following two become really the same:
>
> print list(adict)
> for k in adict: ...
>
> print list(adict.keys())
> for k in adict.keys(): ...

Alas, the consensus has moved away from simple iterators to less
lightweight "views":

http://svn.python.org/view/peps/trunk/pep-3106.txt?rev=53096&view=markup

"The objects returned by the .keys() and .items() methods behave like
sets with limited mutability; the allow removing elements, but not
adding them.(...) The object returned by the values() method behaves
like a multiset."

I for one am not convinced that adding three new types is worth the
complexity and the error-proneness of having two new
similar-but-not-quite-the-same APIs with sets. Not only iteration is
arguably the most common operation on a view, but the cost (in extra
keystrokes and runtime performance) of populating any container that
the user may need from an iterator is pretty low.

George




More information about the Python-list mailing list