[New-bugs-announce] [issue31254] WeakKeyDictionary/Mapping doesn't call __missing__

Antony Lee report at bugs.python.org
Tue Aug 22 03:31:12 EDT 2017

New submission from Antony Lee:

The following example, which raises a KeyError, shows that in a WeakKeyDictionary subclass that defines __missing__, that method doesn't get called.

    from weakref import WeakKeyDictionary

    class WeakKeyDictionaryWithMissing(WeakKeyDictionary):
        __missing__ = lambda: print("hello")

    class C: pass

    d = WeakKeyDictionaryWithMissing()

This behavior is technically OK, as object.__missing__ is only documented in the datamodel to be called for dict subclasses, and WeakKeyDictionary is actually not a subclass of dict, but of MutableMapping.

Still, it would seem preferable if either WeakKeyDictionary did use __missing__, or perhaps, more reasonably, Mapping.__getitem__ did so.  (Or, at least, if the WeakKeyDictionary class clearly stated that it does not inherit from dict.  Note that the docs start with "Mapping class that references keys weakly. Entries in the *dictionary* etc." (emphasis mine))

components: Library (Lib)
messages: 300671
nosy: Antony.Lee
priority: normal
severity: normal
status: open
title: WeakKeyDictionary/Mapping doesn't call __missing__
versions: Python 3.6, Python 3.7

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list