Configuration precedence chooses which source wins for each setting before the merged result becomes application state.
Python configuration precedence: merge, validate, then publish
Operation contract
The fixture applies defaults, then file settings, then explicit overrides. All input mappings remain owned by their callers. Unknown keys fail before merging, and the final worker count is validated after precedence has selected it. Publishing one validated dictionary avoids services observing half-applied settings.
Failure and ownership boundary
An override with a null or empty value is still an override unless the protocol defines otherwise. Reading process environment variables would require separate string parsing and a secret policy; this fixture deliberately receives owned mappings instead. Reloading an existing service also needs coordination around the published snapshot. Python tomllib: parse configuration and validate its schema and Python locks: protect the complete inventory transition cover those boundaries.
Working program
def resolve_settings(defaults, file_settings, overrides):
allowed = {"region", "workers"}
for source in (defaults, file_settings, overrides):
if set(source) - allowed:
raise ValueError("unknown setting")
merged = {**defaults, **file_settings, **overrides}
if set(merged) != allowed or merged["region"] not in {"DEL", "BOM"}:
raise ValueError("incomplete settings")
if type(merged["workers"]) is not int or not 1 <= merged["workers"] <= 8:
raise ValueError("invalid workers")
return merged
defaults = {"region": "DEL", "workers": 2}
print(resolve_settings(defaults, {"workers": 3}, {"region": "BOM"}))
print(defaults)
try:
resolve_settings(defaults, {}, {"workers": None})
except ValueError:
print("null override rejected")Output
{'region': 'BOM', 'workers': 3}
{'region': 'DEL', 'workers': 2}
null override rejectedCosts and limits
Merging k total mapping entries takes expected O(k) reference work and retains an outer result. It does not deep-copy nested configuration. This schema permits only immutable scalar values, keeping publication ownership small.
Common Mistakes
- Do not silently ignore an explicit invalid override.
- Validate the final resolved state before replacing live settings.
Connected lessons
Python tomllib: parse configuration and validate its schema, Python shallow and deep copies: preserve aliases deliberately, Python locks: protect the complete inventory transition.
Follow the service contract
Python ChainMap: live configuration layers versus an owned snapshot.
