We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Everyday Standard Library Tools step 10 of 55
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]]]: ...
layersis 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_layeris either negative, which means no patch, or a valid index intolayers.- 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:
- Look up
key. Save its value and the index of its layer in the originallayerslist, not in the reversed chain. If no layer contains the key, use"<missing>"and-1. - If
patch_layeris 0 or more, setlayers[patch_layer][key]topatch_value. The value can beNone. - If
write_throughis notNone, set the key"written"towrite_throughthrough the chain. Values such asFalse,0and""are notNone, so they trigger the write. - Look up
keyagain through the same chain, and get its value and layer index. - 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 layerto tell a missing key from a key whose value isNone. - 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. Ifkeyis"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.
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
Python reference solution
Sign in to track your attempts toward unlocking the reference solution.