Sub topic 5
How default_factory really works
What this chapter assumes
You should already be comfortable with the basics from the previous chapter: creating a defaultdict, passing list or int as its factory, and using it to group or count. You should also know how dict lookup works, what a KeyError is, and how to define a class with methods and inheritance.
This chapter explains what happens inside a defaultdict lookup. Once you know the mechanism, the odd behaviors become predictable. These are keys that appear after a read, get() that ignores the factory, and errors during iteration.
The mechanism: `__missing__`
A defaultdict is a subclass of dict. It adds one attribute, default_factory, and one method, __missing__. It does not override [] lookup.
The built-in dict.__getitem__ has a hook. If the key is not found, and the object's class defines __missing__, Python calls __missing__(key) and returns whatever it returns. If the class does not define it, Python raises KeyError.
defaultdict.__missing__ does three things:
- If
default_factoryisNone, it raisesKeyError(key). - Otherwise it calls
default_factory()with no arguments. - It stores the result under the key, then returns it.
You can call the hook yourself to watch it work:
from collections import defaultdict
d = defaultdict(list)
print(d.default_factory) # <class 'list'>
print(d) # defaultdict(<class 'list'>, {})
print(d.__missing__("a")) # []
print(d) # defaultdict(<class 'list'>, {'a': []})Normally you never call __missing__ directly. Writing d["a"] reaches it automatically, but only when the key is absent.
Which operations call the factory
Only d[key] goes through __missing__. Other ways of reading a dictionary never reach it. The table summarizes the common operations on a defaultdict(list) where the key "k" is absent.
| Operation | Calls the factory? | Result when `"k"` is absent |
|---|---|---|
| `d["k"]` | Yes | Inserts `[]` and returns it |
| `d["k"].append(1)` | Yes | Inserts `[]`, then appends |
| `d["k"] += [1]` | Yes | Reads (inserts `[]`), then stores the new list |
| `d.get("k")` | No | Returns `None`, dictionary unchanged |
| `d.get("k", [])` | No | Returns the given default, dictionary unchanged |
| `"k" in d` | No | Returns `False` |
| `d.pop("k")` | No | Raises `KeyError` |
| `d.pop("k", None)` | No | Returns `None` |
| `del d["k"]` | No | Raises `KeyError` |
| `d.setdefault("k", [9])` | No | Inserts and returns `[9]`, ignoring the factory |
The next example shows the non-inserting operations:
from collections import defaultdict
d = defaultdict(list)
print("a" in d) # False
print(d.get("a")) # None
print(d.get("a", [1])) # [1]
print(len(d)) # 0
try:
d.pop("a")
except KeyError as err:
print("KeyError", err) # KeyError 'a'
print(d["a"]) # []
print(len(d)) # 1Notice that d.get("a") returns None even though the factory would produce []. This is the most common surprise. The get method is inherited unchanged from dict, so a defaultdict gives different answers to d["a"] and d.get("a") for the same missing key.
Reads that insert keys
Because d[key] inserts, a lookup meant only to check a value can grow the dictionary. Here is a typo that goes unnoticed:
from collections import defaultdict
inventory = defaultdict(int)
inventory["widget"] = 5
if inventory["widgit"] > 0: # typo in the key
print("in stock")
print(list(inventory)) # ['widget', 'widgit']The program never raises an error. The misspelled key now exists with the value 0. Reports built from inventory later will include it. A plain dict would have raised KeyError and pointed you at the bug.
Two habits prevent this:
- For a read-only check, use
key in dord.get(key), neverd[key]. - Once you have finished building the structure, convert it to a plain
dictwithdict(d). Later lookups of missing keys then raiseKeyErroragain.
from collections import defaultdict
groups = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
groups[word[0]].append(word)
frozen = dict(groups) # shallow copy without the factory
try:
frozen["z"]
except KeyError:
print("no group z") # no group z
print(frozen) # {'a': ['apple', 'avocado'], 'b': ['banana']}The conversion is shallow. If the values are themselves defaultdict objects, as in a nested structure, those inner dictionaries keep their factories.
Reads that break iteration
Inserting on read has a second consequence. A dictionary cannot change size while you iterate over it. If the loop body reads a missing key from the same defaultdict, the next step of the loop fails:
from collections import defaultdict
d = defaultdict(int, a=1, b=2)
try:
for key in d:
d["c"] # a plain read, but it inserts "c"
except RuntimeError as err:
print(err) # dictionary changed size during iterationIf you need to look up other keys inside a loop, iterate over a snapshot such as list(d) or use get.
The factory takes no arguments
default_factory is called with nothing. Any callable that works with zero arguments is valid. These are common choices:
| Factory | Default value | Typical use |
|---|---|---|
| `int` | `0` | Counting |
| `float` | `0.0` | Summing numbers |
| `list` | `[]` | Grouping into lists |
| `set` | `set()` | Grouping without duplicates |
| `dict` | `{}` | Two-level mappings |
| `str` | `""` | Joining text |
| `lambda: "n/a"` | `"n/a"` | A constant that is not a type's empty value |
| `lambda: defaultdict(int)` | An inner defaultdict | Nested counting |
The factory must be callable or None. Anything else fails when you construct the object:
from collections import defaultdict
try:
defaultdict("unknown")
except TypeError as err:
print(err) # first argument must be callable or NoneA nested structure uses a lambda to create a new inner dictionary for each outer key:
from collections import defaultdict
sales = defaultdict(lambda: defaultdict(int))
sales["north"]["apples"] += 3
sales["north"]["pears"] += 1
sales["south"]["apples"] += 2
print({region: dict(items) for region, items in sales.items()})
# {'north': {'apples': 3, 'pears': 1}, 'south': {'apples': 2}}Each call must return a new object
The factory runs once per missing key. If it returns the same mutable object every time, all keys share that object:
from collections import defaultdict
shared = []
d = defaultdict(lambda: shared)
d["a"].append(1)
d["b"].append(2)
print(d["a"]) # [1, 2]
print(d["a"] is d["b"]) # TruePassing list avoids this, because list() builds a fresh list on each call. A lambda that returns a variable defined outside it does not. Write lambda: [] if you want a lambda that creates a new list.
Changing or removing the factory
default_factory is an ordinary attribute. You can read it, replace it, or set it to None:
from collections import defaultdict
d = defaultdict(int)
d["a"] += 1
d.default_factory = None # now behaves like a plain dict for missing keys
try:
d["b"]
except KeyError:
print("KeyError for 'b'") # KeyError for 'b'
print(d["a"]) # 1Setting the factory to None is a lightweight way to "freeze" a dictionary in place. The object keeps its type and its data, but missing keys raise errors again. Passing None to the constructor has the same effect from the start.
Constructor arguments
The first positional argument is the factory. Everything after it is passed to the normal dict constructor, so you can supply initial items as a mapping, as pairs, or as keyword arguments:
from collections import defaultdict
a = defaultdict(int, {"x": 1})
b = defaultdict(list, [("k", [1, 2])])
c = defaultdict(int, y=5)
print(a, b, c, sep="\n")
# defaultdict(<class 'int'>, {'x': 1})
# defaultdict(<class 'list'>, {'k': [1, 2]})
# defaultdict(<class 'int'>, {'y': 5})The factory does not apply to these initial items. It applies only to keys that are missing later.
Writing your own `__missing__`
Because defaultdict is just dict plus __missing__, you can write the hook yourself. A dict subclass with a __missing__(self, key) method gets the same behavior. Unlike a factory, your method receives the key, so the default can depend on it.
class SquareDict(dict):
def __missing__(self, key):
value = key * key
self[key] = value
return value
squares = SquareDict()
print(squares[4]) # 16
print(squares) # {4: 16}
print(4 in squares) # TrueThe method decides whether to insert. defaultdict always inserts, but your hook does not have to. A hook that returns a value without storing it gives the "read as zero, never store" behavior you saw in Counter:
class ZeroDict(dict):
def __missing__(self, key):
return 0
z = ZeroDict(a=1)
print(z["b"]) # 0
print("b" in z) # False
print(z) # {'a': 1}If you want defaultdict behavior with a key-aware factory, subclass defaultdict and override __missing__:
from collections import defaultdict
class KeyedDefault(defaultdict):
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
value = self.default_factory(key) # factory receives the key
self[key] = value
return value
paths = KeyedDefault(lambda name: f"/data/{name}.csv")
print(paths["users"]) # /data/users.csv
print(dict(paths)) # {'users': '/data/users.csv'}What happens when the factory fails
The factory runs before anything is stored. If it raises an exception, the key is not inserted and the exception propagates to the caller:
from collections import defaultdict
def broken():
raise ValueError("cannot build a default")
d = defaultdict(broken)
try:
d["a"]
except ValueError as err:
print(err) # cannot build a default
print("a" in d) # FalseA factory that returns None is not a failure. The value None is stored as the default. Do not confuse that case with default_factory=None, which means "no factory" and raises KeyError.
Copying and pickling
The factory travels with the object in most situations:
d.copy()andcopy.copy(d)return adefaultdictwith the same factory.repr(d)shows the factory, as indefaultdict(<class 'list'>, {}).json.dumps(d)works, because the object is adictsubclass. The output has no trace of the factory.- Pickling works with factories that can be found by name, such as
listor a function defined at module level. It fails with a lambda, because pickle stores functions by name and a lambda has none. If you must pickle adefaultdict, use a named function.
Summary of the rules
d[key]on a missing key calls__missing__. Thedefaultdictversion calls the factory with no arguments, stores the result, and returns it.- Only
d[key]does this. The methodsget,in,pop,setdefault, anddeldo not call the factory. - A read that inserts changes the dictionary. Typos create keys, and loops over the dictionary can fail.
- The factory must return a fresh object on each call if the default is mutable.
- For defaults that depend on the key, or for defaults that should not be stored, write a
__missing__method.
Exercises
Exercise
Given d = defaultdict(list), what do d.get("x"), "x" in d, and len(d) return, in that order, and what does len(d) return after a following d["x"]?
Show answer
d.get("x") returns None, "x" in d is False, and len(d) is 0. After d["x"] has run, len(d) is 1. Only the indexing form calls __missing__, which inserts an empty list. The get method and the in operator never call the factory, so they leave the dictionary unchanged.
Exercise
A script uses stock = defaultdict(int) and checks if stock[item] == 0: print("sold out") for every item a customer asks about. Later, a report loops over stock and lists "sold out" items that the shop never sold. What is the cause, and how would you change the check?
Show answer
The check stock[item] is an indexing read, so each unknown item gets inserted with the value 0. The report then sees those items as real entries. Change the check to if stock.get(item, 0) == 0:, which reads without inserting. Alternatively, test item in stock first, or convert stock to a plain dict before the checks begin.
Exercise
What is wrong with d = defaultdict(lambda: shared_list) where shared_list = [] was defined earlier, and how do you fix it?
Show answer
The lambda returns the same list object for every missing key, so all keys share one list and an append under one key shows up under every key. Fix it by passing list as the factory, or by writing lambda: [], so that each call builds a new list.
Exercise
Write a dict subclass named Echo such that Echo()["abc"] returns the string "abc" and does not store the key. Which dictionary operations will still treat "abc" as missing afterwards?
Show answer
Define class Echo(dict): with def __missing__(self, key): return key. Because the method never assigns self[key], nothing is stored. Afterwards "abc" in e is False, len(e) is 0, e.get("abc") is None, and e.pop("abc") raises KeyError. Only e["abc"] returns the string, because it is the only operation that calls __missing__.
Exercise
Why does the following code raise an error, and what is the fix? d = defaultdict(int, a=1), then for k in d: d["b"].
Show answer
Reading d["b"] inserts the key "b", which changes the dictionary's size during iteration. Python raises RuntimeError: dictionary changed size during iteration on the next loop step. Fix it by iterating over a snapshot, as in for k in list(d):, or by reading with d.get("b"), which does not insert.