Deep Merge Layered Configuration Maps
Merge nested configuration mappings layer by layer, replacing scalars and lists while keeping the default tree untouched.
Code
from __future__ import annotations
from collections.abc import Mapping
from copy import deepcopy
from typing import Any
def deep_merge(
base: Mapping[str, Any],
override: Mapping[str, Any],
) -> dict[str, Any]:
merged = deepcopy(dict(base))
for key, value in override.items():
current = merged.get(key)
if isinstance(current, Mapping) and isinstance(value, Mapping):
merged[key] = deep_merge(current, value)
else:
merged[key] = deepcopy(value)
return merged
def resolve_layers(*layers: Mapping[str, Any]) -> dict[str, Any]:
result: dict[str, Any] = {}
for layer in layers:
result = deep_merge(result, layer)
return result
def main() -> None:
defaults = {
"server": {"host": "127.0.0.1", "port": 8000, "tls": False},
"features": ["search"],
}
file_config = {"server": {"port": 9000}, "features": ["search", "export"]}
env_config = {"server": {"host": "0.0.0.0"}}
resolved = resolve_layers(defaults, file_config, env_config)
print(resolved)
assert resolved["server"]["port"] == 9000
assert resolved["server"]["host"] == "0.0.0.0"
assert resolved["features"] == ["search", "export"]
assert defaults["server"]["port"] == 8000
if __name__ == "__main__":
main()
What the code does
Deep Merge Layered Configuration Maps comes down to the functions deep_merge, resolve_layers and main.
for key, value in override.items() is the loop that carries the per-item work. annotations, Mapping, deepcopy, Any are the only symbols borrowed from __future__ — the coupling is explicit and narrow.
Caveats
- External dependency:
__future__— install it before running the snippet.
Applying it
The main signature reads def deep_merge( base: Mapping[str, Any], override: Mapping[str, Any], ) -> dict[str, Any]
Treat main as the orchestrator calling resolve_layers in a fixed order.
Statements that matter
def resolve_layers(*layers: Mapping[str, Any]) -> dict[str, Any]:
result: dict[str, Any] = {}
for layer in layers:
result = deep_merge(result, layer)
return result
def deep_merge(
base: Mapping[str, Any],
override: Mapping[str, Any],
) -> dict[str, Any]:
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Gitignore Template BuilderCompose clean .gitignore files by combining Node, Python, Go, Rust, Java, OS, IDE, and Docker presets with deduplication and custom rules.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- Do I need to install anything before running this?
- Yes: `__future__` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.