[Python-3000] have iter(mapping) generate (key, value) pairs

Nick Coghlan ncoghlan at gmail.com
Sat Jun 3 01:54:33 CEST 2006

Steven Bethard wrote:
> Note that even though the `Language Reference`_ defines mappings in
> terms of __len__, __getitem__, __setitem__, __delitem__ and __iter__,
> UserDict.DictMixin.update has to assume that all mappings have a
> .keys() method.

A slightly different proposal:

Add an iteritems() builtin with the following definition:

     def iteritems(obj):
         # Check for mapping first
             items = obj.items      # or __items__ if you prefer
         except AttributeError:
             return iter(items())
         # Check for sequence next
         if hasattr(obj, "__getitem__"):
             return enumerate(obj)
         # Fall back on normal iteration
         return iter(obj)

Then update the language reference so that the presence of of an items() (or 
__items__()) method is the defining characteristic that makes something a 
mapping instead of a sequence. After all, we've been trying to think of a way 
to denote that anyway.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-3000 mailing list