Layered Settings Without Merging: Python's ChainMap

This article explains how collections.ChainMap searches several mappings in order without copying them, why writes and deletions reach only the first mapping, and what its lookups cost compared with a merged dictionary.

A green tree python with blue markings resting its head on layered coils over a mossy branch against a muted background
Photo by Matteo Vella on Unsplash

Configuration usually comes in layers, such as built-in defaults, values from the environment and options given by the user, and a program must find each setting in the most specific layer that defines it. The present article addresses collections.ChainMap, which groups several mappings into a single view and searches them in order without merging them. Many games load modifications in a priority order, so that a modification replaces a file of the base game without altering it, and removing the modification restores the original. This means that a ChainMap returns the value of the first mapping that contains a key, while the mappings behind it remain intact and visible for every key that the earlier ones do not define. The analogy, however, stops at this point, because a ChainMap writes and deletes only in its first mapping, so it cannot change or remove a value that lives in a later layer. The article examines lookups, live views and child layers, measures the cost of the chain and analyses the errors that its write rules produce. Answering a lookup across several layers of data without copying any of them is the secret weapon of ChainMap.

Lookups Across Layers

A ChainMap is built from mappings ordered from the most to the least specific, and a lookup scans them in that order until it finds the key. The mappings are held by reference, not copied, so a change in any of them is visible through the chain immediately, which a dictionary merged with update or | cannot offer. The method new_child returns a new chain with an extra mapping in front, and the property parents returns the chain without its first mapping, which together model nested scopes in the way that the documentation describes for interpreters and template engines.

from collections import ChainMap

defaults = {"theme": "light", "language": "en"}
user = {"theme": "dark"}
settings = ChainMap(user, defaults)

print(settings["theme"], settings["language"])  # Output: dark en
defaults["language"] = "es"
print(settings["language"])                     # Output: es

session = settings.new_child({"theme": "contrast"})
print(session["theme"], settings["theme"])      # Output: contrast dark
print(session.parents["theme"])                 # Output: dark
print(list(settings))                           # Output: ['theme', 'language']

The change to defaults appears in the chain without any further step, and the session layer overrides the theme without touching the user settings. Iteration scans the mappings from last to first, so keys appear in the order of the least specific layer, followed by keys that only the earlier layers define. The documentation describes this structure as a way to simulate nested scopes; the interpreter itself does not use ChainMap for its own variables. A temporary layer created with new_child follows the same discipline as the resources managed in the article devoted to ExitStack: it is added for a limited task and discarded afterwards, leaving everything below unchanged.

Pitfalls of ChainMap

The chain reads from every layer but writes to one, and it computes some answers anew on every call, so most errors come from expecting it to behave like a merged dictionary. Six pitfalls are distinguished, which are the following:

  1. Writes go to the first mapping. Assigning a key through the chain stores it in the first mapping, even when the key was found in a later one.
  2. Deletions reach only the first mapping. Deleting a key that exists only in a later layer raises KeyError, and deleting it from the first layer reveals the value below instead of removing the key.
  3. None shadows lower layers. A layer that stores None for an unset option hides the default, because the key is present.
  4. Lookups grow with the number of layers. A key that lives in a deep layer, or a key that is missing, requires a lookup in every mapping.
  5. Size and iteration rebuild the union. len, iteration and equality combine every layer on each call, so their cost grows with the total number of keys.
  6. Live views. Because the mappings are shared, a change made elsewhere to a layer, or to the list maps, changes every chain that uses it.

The first three pitfalls are reproduced in the following example.

from collections import ChainMap

defaults = {"theme": "light", "language": "en"}
user = {"theme": "dark", "language": None}
settings = ChainMap(user, defaults)

settings["font"] = "mono"
print(user)  # Output: {'theme': 'dark', 'language': None, 'font': 'mono'}
try:
    del settings["missing"]
except KeyError as error:
    print(error)  # Output: "Key not found in the first mapping: 'missing'"
print(settings["language"])  # Output: None

cleaned = ChainMap({k: v for k, v in user.items() if v is not None}, defaults)
print(cleaned["language"])  # Output: en

The new key lands in the user layer, the deletion fails because it never looks beyond the first mapping, and the explicit None hides the default language until the layer is filtered. When None is itself a meaningful setting, a dedicated marker for an unset option is preferable to filtering, as discussed in the article devoted to the Sentinel pattern. When writes must update whichever layer holds a key, the documentation proposes a DeepChainMap subclass that overrides __setitem__ and __delitem__.

Measuring the Cost of the Chain

The absence of copying has a price that is paid on every lookup, and the following measurement compares a key stored in the last of fifty layers with the same key in a merged dictionary.

import timeit
from collections import ChainMap

layers = [{f"k{i}": i} for i in range(50)]
chain = ChainMap(*layers)
merged = {}
for layer in reversed(layers):
    merged.update(layer)

deep = timeit.timeit(lambda: chain["k49"], number=100_000)
flat = timeit.timeit(lambda: merged["k49"], number=100_000)
print(deep > 10 * flat)  # Output: True

On CPython 3.12, the lookup in the chain took about 150 times as long as in the merged dictionary, and len of a chain of two dictionaries of 100,000 keys each took about 3.4 milliseconds per call, because it builds the union every time. A chain with a few layers and frequent changes in the defaults is the appropriate case; a chain with many layers that is read in a tight loop should be merged once.

Choosing Between a Chain and a Merge

Consequently, the choice between a chain and a merged dictionary depends on how often the layers change, how many there are and where writes must go, as the following table summarizes.

Situation Recommended approach
Few layers that change while the program runs ChainMap
Layers that never change after start-up A merged dictionary, built with `
Many layers read in a tight loop A merged dictionary
Temporary overrides, such as a request or a scope new_child and parents
Writes that must update the layer that holds the key A DeepChainMap subclass
Unset options stored as None Filter them, or use a sentinel
Command-line options over environment over defaults ChainMap(args, os.environ, defaults)

Conclusion

It is concluded that ChainMap searches several mappings in order without copying them, that it reflects every change in its layers immediately, and that new_child and parents model nested layers of configuration or scope. This magic has two limits: writes and deletions reach only the first mapping, and lookups, size and iteration cost more as layers and keys accumulate. Assembling a complex object step by step, with a separate object that collects the parts before the final one is created, is the purpose of the Builder pattern, which is developed in a future article of this series.