S
Steven Bethard
Sorry if this is a repost -- it didn't appear for me the first time.
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. 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 why does
UserDict.DictMixin require keys() to be defined?
py> class D(object, UserDict.DictMixin):
.... """Simple dict wrapper that implements container protocol"""
.... def __init__(self, dict): self.dict = dict
.... def __len__(self, key): return len(self.dict)
.... def __getitem__(self, key): return self.dict[key]
.... def __setitem__(self, key, value): self.dict[key] = value
.... def __delitem__(self, key): del self.dict[key]
.... def __iter__(self): return iter(self.dict)
.... def __contains__(self, key): return key in self.dict
....
py> d = D(dict(a=1, b=2))
py> d.clear()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "C:\Program Files\Python\lib\UserDict.py", line 114, in clear
for key in self.keys():
AttributeError: 'D' object has no attribute 'keys'
py> d.keys()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: 'D' object has no attribute 'keys'
I thought about submitting a patch, but I couldn't think of a way that
didn't raise backwards compatibility concerns...
Steve
[1]http://docs.python.org/ref/sequence-types.html
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. 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 why does
UserDict.DictMixin require keys() to be defined?
py> class D(object, UserDict.DictMixin):
.... """Simple dict wrapper that implements container protocol"""
.... def __init__(self, dict): self.dict = dict
.... def __len__(self, key): return len(self.dict)
.... def __getitem__(self, key): return self.dict[key]
.... def __setitem__(self, key, value): self.dict[key] = value
.... def __delitem__(self, key): del self.dict[key]
.... def __iter__(self): return iter(self.dict)
.... def __contains__(self, key): return key in self.dict
....
py> d = D(dict(a=1, b=2))
py> d.clear()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "C:\Program Files\Python\lib\UserDict.py", line 114, in clear
for key in self.keys():
AttributeError: 'D' object has no attribute 'keys'
py> d.keys()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: 'D' object has no attribute 'keys'
I thought about submitting a patch, but I couldn't think of a way that
didn't raise backwards compatibility concerns...
Steve
[1]http://docs.python.org/ref/sequence-types.html