Skip to content

← Everyday Standard Library Tools step 10 of 55

Medium Primitives

Resolve a Setting and Report the Layer It Came From

A config loader stacks layers such as defaults, environment and command line, and the highest layer that sets a key wins. Write solve, which looks up one key through a ChainMap and reports the value and the layer it came from. Then it changes the layers and looks the key up again.

solve([{"port": 8000}, {}], "port", 1, 9000, None)
# (8000, 0, 9000, 1, [{"port": 8000}, {"port": 9000}])

The inputs

def solve(
    layers: list[dict[str, object]],
    key: str,
    patch_layer: int,
    patch_value: object,
    write_through: object,
) -> tuple[object, int, object, int, list[dict[str, object]]]: ...
  • layers is a non-empty list of dicts, from lowest to highest priority, such as [defaults, environment, command_line]. The last layer that contains the key wins.
  • patch_layer is either negative, which means no patch, or a valid index into layers.
  • You do not need to check for inputs outside these rules.

What to write

Build one ChainMap[str, object] over the layers in reverse order, so the highest priority comes first. Do not merge or copy the layers. Then do these steps in order:

  1. Look up key. Save its value and the index of its layer in the original layers list, not in the reversed chain. If no layer contains the key, use "<missing>" and -1.
  2. If patch_layer is 0 or more, set layers[patch_layer][key] to patch_value. The value can be None.
  3. If write_through is not None, set the key "written" to write_through through the chain. Values such as False, 0 and "" are not None, so they trigger the write.
  4. Look up key again through the same chain, and get its value and layer index.
  5. Return (before_value, before_index, after_value, after_index, layers), with the layers as they are after the changes.

Rules to watch

  • Use key in layer to tell a missing key from a key whose value is None.
  • A layer can hold the string "<missing>" as a real value. The index then shows that the key is present.
  • A patch to a lower layer does not override a higher layer that also has the key.
  • The write in step 3 goes to layers[-1] only, and leaves any "written" key in the other layers alone. If key is "written", the second lookup must see the new value.

The second lookup sees the changes because the chain holds the layers themselves. Building that one live view is the point of the exercise, even though the tests can check only the results.