What is a mapping object, according to dict type?
It seems that implementing only keys
and __getitem__
is sufficient.
>>> class mydict:
... def keys(self):
... return 'xyz'
... def __getitem__(self, item):
... return 'potato'
...
>>> dict(mydict())
{'x': 'potato', 'y': 'potato', 'z': 'potato'}
From the source code for CPython, this comment:
/* We accept for the argument either a concrete dictionary object,
* or an abstract "mapping" object. For the former, we can do
* things quite efficiently. For the latter, we only require that
* PyMapping_Keys() and PyObject_GetItem() be supported.
*/
So, "the minimal interface required for dict(mapping) to work" appears to be .keys()
and .__getitem__()
.
Example program:
class M:
def keys(self):
return [1,2,3]
def __getitem__(self, x):
return x*2
m = M()
d = dict(m)
assert d == {1:2, 2:4, 3:6}
The glossary defines it as:
A container object that supports arbitrary key lookups and implements the methods specified in the Mapping or MutableMapping abstract base classes. Examples include
dict
,collections.defaultdict
,collections.OrderedDict
andcollections.Counter
.
So it looks like the minimal list of methods to meet the definition is __getitem__
, __iter__
, __len__
, __contains__
, keys
, items
, values
, get
, __eq__
, and __ne__
. Although I bet the dict constructor does not actually need all of those.