ML Foundations
Why dict.setdefault evaluates a default for an existing key
Avoid running an expensive default factory on cache hits with an explicit membership check.
![Example results for Why dict.setdefault evaluates a default for an existing key. existing: ['a'] factory calls: 1](/assets/covers/python-setdefault-eager-factory.png)
Evidence and testing
Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.
The factory runs before the lookup
Calling cache.setdefault(key, build()) evaluates build() as an argument before the method is called. Even when the key exists, the factory runs and its result is unused. This follows Python call evaluation rules, not a special cache behavior. [1, 2]
This can matter if the default requires work or has side effects. Passing a cheap literal may be acceptable, but passing a function call does not defer that function until a miss.
Guard the factory on a miss
Run python examples/python_setdefault_eager_factory.py. The example records a call for setdefault on an existing key, while the membership guard leaves that count unchanged. It then creates the missing key and checks an empty list that is present. [1, 2]
Testing membership distinguishes a missing key from a present falsey value. A shortcut using an or expression can wrongly treat an empty list or zero as a cache miss. The exact output below comes from the example.
Executed with Python 3.12.14; stdout and checksum are in private evidence.
calls = []
def build():
calls.append('built')
return []
cache = {'present': []}
cache.setdefault('present', build()).append('a')
print('existing:', cache['present'], 'factory calls:', len(calls))
if 'present' not in cache:
cache['present'] = build()
cache['present'].append('b')
print('guard existing:', cache['present'], 'factory calls:', len(calls))
if 'missing' not in cache:
cache['missing'] = build()
cache['missing'].append('c')
print('guard missing:', cache['missing'], 'factory calls:', len(calls))
cache['empty'] = []
if 'empty' not in cache:
cache['empty'] = build()
print('falsey present:', cache['empty'], 'factory calls:', len(calls))
assert len(calls) == 2 and cache['empty'] == []
Recorded output
existing: ['a'] factory calls: 1 guard existing: ['a', 'b'] factory calls: 1 guard missing: ['c'] factory calls: 2 falsey present: [] factory calls: 2
Choose a policy for the real cache
The explicit guard makes creation conditional and stores the result on a miss. For an ordinary dictionary, it preserves a value already stored under the key, including an empty list. If the factory raises an exception, the assignment does not complete. [1, 2]
The example is single-threaded and does not establish atomic behavior when multiple workers share state. It counts calls rather than measuring speed, and it does not claim that membership checking always improves performance. Choose a synchronization strategy separately when concurrent creation matters.