[Python-ideas] should `dict` supply a default `__missing__` implementation?

Matt Gilson matt at getpattern.com
Wed Jun 29 13:47:13 EDT 2016


The following code raises an `AttributeError`:

>>> class D(dict):
...     def __missing__(self, k):
...          super(D, self).__missing__(k)
...
>>> d = D()
>>> d['key']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __missing__
AttributeError: 'super' object has no attribute '__missing__'

I find this behavior to be a little bit odd as I would have expected the
default implementation to have a `__missing__` method and I would expect
the `__missing__` method to raise an appropriate `KeyError`.  I think that
this would facilitate a class hierarchy where each class can decide "I
don't know hot to handle this missing key, maybe something further up the
MRO does".  Currently, to do that (and adhere to the ["Super considered
Super"](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/)
methodology) you'd have to add an extra base-class in the hierarchy which
seems unnecessary.

Obviously this is probably a pretty niche case and may not be worth
considering, but I thought I'd throw it out there just in case.

Also, FWIW, I believe that the current behavior is correct based on [the
documentation](https://docs.python.org/2/library/stdtypes.html#dict) (under
`d[key]`).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160629/5f18fdab/attachment.html>


More information about the Python-ideas mailing list