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

Paul Moore p.f.moore at gmail.com
Wed Jul 6 07:19:24 EDT 2016

On 6 July 2016 at 06:51, Ethan Furman <ethan at stoneleaf.us> wrote:
> I will admit I don't understand the push-back against adding __missing__

I thought that the idea was that __missing__ *if present* defined an
alternative behaviour for missing keys. If it's not present, the
default behaviour (key error) applies.

Now it's certainly the case that having the base class provide an
implementation of __missing__ that had the default behaviour would do
the same - and in a "pure object oriented" sense, that's the way
something like this "should" be implemented. But historically, it's
not that way, and I suspect that it was much easier to bolt on an "if
there's a __missing__ use it, otherwise proceed as before" check than
it would have been to pull out the existing behaviour into a new
(overridable) method.

Python's never been particularly concerned about following pure OOP
principles - "practicality beats purity" is relevant here. And I think
the problem is that there's no obvious gain to making the default
behaviour a concrete __missing__ method (and it would result in code
churn in one of the most central and performance-sensitive areas of

So the push-back is mostly in the nature of "if it ain't broke, don't
fix it" - and I don't think there's been a compelling (i.e., founded
in practical issues) argument that anything is broken here. The
original issue involved super() - and my understanding is that super()
is intended for "co-operative" multiple inheritance, not for arbitrary
"pass this method on without me needing to know the class hierarchy"

Specifically, in

    class D(dict):
        def __missing__(self, k):
             super(D, self).__missing__(k)

it's not clear why D needs a __missing__ method at all, if all it's
doing is delegating to dict - we know dict has no __missing__ so D can
also simply omit the method. (Possibly if D is being designed as a MI
base class, that's not acceptable - but in which case there's not
enough information here about the requirement to comment - maybe
manually raising KeyError here is enough).


More information about the Python-ideas mailing list