why does UserDict.DictMixin use keys instead of __iter__?

Steven Bethard steven.bethard at gmail.com
Tue Jan 4 09:35:57 EST 2005

John Machin wrote:
> Steven Bethard wrote:
>>So I was looking at the Language Reference's discussion about
>>emulating container types[1], and nowhere in it does it mention that
>> .keys() is part of the container protocol.
> I don't see any reference to a "container protocol".

Sorry, I extrapolated "container protocol" from this statement:

"Containers usually are sequences (such as lists or tuples) or mappings 
(like dictionaries), but can represent other containers as well. The 
first set of methods is used either to emulate a sequence or to emulate 
a mapping"

and the fact that there is a "sequence protocol" and a "mapping protocol".

But all I was really reading from this statement was that the "first set 
of methods" (__len__, __getitem__, __setitem__, __delitem__ and 
__iter__) were more integral than the second set of methods (keys(), 
values(), ...).

> What I do see is
> (1) """It is also recommended that mappings provide the methods keys(),
> ..."""

You skipped the remaining 13 methods in this list:

"It is also recommended that mappings provide the methods keys(), 
values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), 
itervalues(), iteritems(), pop(), popitem(), copy(), and update() 
behaving similar to those for Python's standard dictionary objects."

This is the "second set of methods" I mentioned above.  I don't 
understand why the creators of UserDict.DictMixin decided that keys(), 
from the second list, is more important than __iter__, from the first list.

>>Because of this, I would assume that to
>>use UserDict.DictMixin correctly, a class would only need to define
>>__getitem__, __setitem__, __delitem__ and __iter__.
> So I can't see why would you assume that, given that the docs say in
> effect "you supply get/set/del + keys as the building blocks, the
> DictMixin class will provide the remainder". This message is reinforced
> in the docs for UserDict itself.

Sorry, my intent was not to say that I didn't know from the docs that 
UserDict.DictMixin required keys().  Clearly it's documented.  My 
question was *why* does it use keys()?  Why use keys() when keys() can 
be derived from __iter__, and __iter__ IMHO looks to be a more basic 
part of the mapping protocol.

> In any case, isn't UserDict past history? Why are you mucking about
> with it?

UserDict is past history, but DictMixin isn't.  As you note, DictMixin 
is even mentioned in the section of the Language Reference that we're 

"The UserDict module provides a DictMixin class to help create those 
methods from a base set of __getitem__(), __setitem__(), __delitem__(), 
and keys()."


More information about the Python-list mailing list