[Python-ideas] should `dict` supply a default `__missing__` implementation?
Guido van Rossum
guido at python.org
Wed Jun 29 14:56:02 EDT 2016
The argument against adding `dict.__missing__()` is that it would just
a shortcut to raise KeyError with certain parameters.
The purpose of `__missing__` is to give you a hook to override how the
base class handles missing keys in `__getitem__`. In order to define
this hook you must necessarily subclass dict.
IMO the idea that there's always a superclass you can call is silly --
you should distinguish between cases where you *override* a method vs.
cases where you *define* it. In this case you are required to *define*
`__missing__`.
But I may be missing something...
On Wed, Jun 29, 2016 at 11:29 AM, Michael Selik <michael.selik at gmail.com> wrote:
> On Wed, Jun 29, 2016 at 1:47 PM Matt Gilson <matt at getpattern.com> wrote:
>>
>> The following code raises an `AttributeError`:
>> >>> class D(dict):
>> ... def __missing__(self, k):
>> ... super(D, self).__missing__(k)
>> ...
>>
>> I find this behavior to be a little bit odd as I would have expected the
>> default implementation to have a `__missing__` method
>
>
> The behavior of a dictionary key-lookup checking for __missing__ parallels
> the way a standard class does attribute-lookup, checking for __getattr__.
>
> I'm guessing the non-existence of __missing__ on the built-in dict type (and
> the non-existence of __getattr__ on the base object type) allows for some
> speed optimizations in the interpreter. If so, then the tradeoff of needing
> to provide an extra base class shim for your multiple inheritance hierarchy
> seems reasonable. Does anyone know the original reason for not having
> __missing__ defined on the builtin type?
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
--
--Guido van Rossum (python.org/~guido)
More information about the Python-ideas
mailing list