Computing Values Only When a Key Is Missing: Python's __missing__

This article explains when Python calls the __missing__ method of a dict subclass, how it differs from defaultdict and Counter, what a miss costs, and which pitfalls, from recursion to accidental insertion, its use involves.

A green tree python resting its head among its own tight coils on a branch, lit softly against a dark background
Photo by Samuel Weissgerber on Unsplash

A dictionary normally answers a request for an absent key with KeyError, so every caller must check for the key, supply a default or catch the exception. The present article addresses the special method __missing__, which lets a subclass of dict decide what an absent key produces at the single place where the lookup happens. Some game universes provide an appropriate image: a planet does not exist until a traveller arrives at it, and from that moment it is generated and remains part of the universe. This means that a dictionary with __missing__ can compute the value of a key the first time it is requested, store it, and serve it directly on every later request. The analogy, however, stops at this point, because such a planet is generated from a fixed seed, whereas __missing__ may compute anything or nothing, and only the indexing operation d[key] triggers it. The article explains exactly when the method is called, compares it with defaultdict and Counter, measures its cost and analyses its pitfalls. Deciding, inside the dictionary itself, what an absent key means, with the key in hand and without touching any caller, is the secret weapon of __missing__.

When Python Calls missing

The method belongs to the lookup d[key]: when a subclass of dict defines __missing__ and the key is absent, the lookup calls the method with the key and returns its result. The documentation is explicit that no other operation calls it, so get, in, pop and setdefault keep their ordinary behaviour, and the method must be defined on the class, because an instance attribute with that name is ignored.

class Profiles(dict):
    def __missing__(self, key):
        print(f"loading {key}")
        value = f"profile of {key}"
        self[key] = value
        return value

users = Profiles()
print(users["alice"])
print(users["alice"])
print(users.get("bob"), "bob" in users)
# Output: loading alice
# Output: profile of alice
# Output: profile of alice
# Output: None False

The first lookup loads the profile and stores it, so the second one finds the key without calling the method; get and in see an ordinary dictionary and neither load nor store anything. Storing the value is a decision of the method, not a rule: a method that only returns a value, without assigning it, answers every miss anew and leaves the dictionary unchanged. The hash table that serves the stored keys is the one described in the article devoted to the dictionary, and __missing__ adds a step only after that search has failed.

defaultdict, Counter and format_map

The standard library already uses the hook in several places, and each one fixes a different policy for absent keys. collections.defaultdict calls its default_factory without arguments and inserts the result, collections.Counter returns zero without inserting anything, and str.format_map accepts any mapping, so a subclass with __missing__ can leave unknown placeholders intact.

from collections import Counter, defaultdict

groups = defaultdict(list)
groups["fruit"].append("apple")
print(dict(groups))  # Output: {'fruit': ['apple']}

counts = Counter()
print(counts["pear"], counts)  # Output: 0 Counter()

class KeepPlaceholders(dict):
    def __missing__(self, key):
        return "{" + key + "}"

template = "{name} lives in {city}"
print(template.format_map(KeepPlaceholders(name="Ada")))
# Output: Ada lives in {city}

The defaultdict is the right tool when the default does not depend on the key, and Counter when absent keys mean zero. A custom __missing__ is needed when the value depends on the key itself, as in the template, which receives the name of the placeholder and rebuilds it. Subclasses of collections.UserDict honour the method as well, which matters when other methods of the mapping are also overridden.

Pitfalls of missing

The hook is narrow by design, so most errors come from expecting it in operations that never call it, or from forgetting that it runs as ordinary Python code on every miss. Six pitfalls are distinguished, which are the following:

  1. Expecting it from get or in. Only d[key] calls the method; code that uses get sees an ordinary dictionary.
  2. Recursion. A method that reads self[key] calls itself again for the same absent key and ends in RecursionError.
  3. Insertion by reading. A method that stores the value, like defaultdict, adds a key even when the caller only wanted to inspect it, for example in a condition.
  4. An instance attribute. Assigning __missing__ to an instance has no effect, because special methods are looked up on the type.
  5. The cost of a miss. Each miss calls a Python function, several times slower than dict.get.
  6. Unbounded growth. A method that stores every requested key keeps all of them, which turns typing errors and untrusted input into permanent entries.

The second and third pitfalls are reproduced in the following example.

from collections import defaultdict

class Broken(dict):
    def __missing__(self, key):
        return self[key]

try:
    Broken()["x"]
except RecursionError:
    print("RecursionError")  # Output: RecursionError

tags = defaultdict(list)
if tags["typo"]:
    pass
print(dict(tags))  # Output: {'typo': []}

The broken method calls itself until the interpreter stops it, because self[key] inside __missing__ triggers the same lookup; the stored value must be assigned with self[key] = value and returned, never read back. The condition on tags["typo"] was meant to read, yet it inserted an empty list, so code that only inspects such a dictionary should use get or in.

Choosing How to Handle Absent Keys

Consequently, the decision depends on how often keys are absent and on whether the absent value depends on the key. On CPython 3.12, a lookup of a present key took about 38 nanoseconds in a subclass with __missing__ and about 34 in a plain dictionary, while a miss answered by __missing__ took about 177 nanoseconds against 28 for dict.get, as the following table summarizes together with the alternatives.

Situation Recommended approach
A default that does not depend on the key dict.get, setdefault or defaultdict
Counting, with zero for absent keys collections.Counter
A value computed from the key and stored A dict subclass with __missing__
Placeholders that must survive formatting str.format_map with a __missing__ subclass
Reading without inserting get or in, never d[key] on such a dictionary
Caching the results of a function functools.cache or lru_cache
Absent keys that signal an error A plain dict and KeyError

The choice between checking and catching for ordinary dictionaries is examined in the article devoted to EAFP and LBYL, and caching the results of a function rather than the entries of a mapping is the purpose of the decorators described in the article devoted to lru_cache.

Conclusion

It is concluded that __missing__ lets a subclass of dict decide what an absent key produces, that only the lookup d[key] calls it, and that it receives the key, which distinguishes it from the factory of defaultdict. This magic must be used with its limits in mind: the method must not read the key it is computing, storing values turns every read into a possible insertion, and each miss costs a call to Python code. Counting hashable objects with a dictionary that answers zero for every absent key, a direct application of this hook, is the purpose of collections.Counter, which is developed in a future article of this series.