runtime
360 / 500
question 360 Memory & Python Internals · hard

Merge configuration layers without sharing anything

A service builds its settings from a base layer and an environment layer. Write merge_config(base, override). Nested dictionaries are merged key by key; any other value in override replaces the base value. The result is handed to code that edits it, so it must not share any mutable object (dictionary or list) with either input, and neither input may change.

Functionmerge_config(base, override)
Mergingfor each key in override: if both values are dictionaries, merge them the same way; otherwise the override value replaces the base value (a list replaces a list, it isn't joined)
Orderkeys keep the base's order, then keys only in override in their order
Returnsa new dictionary that shares no dictionary or list with base or override
Examples
callmerge_config({'db': {'host': 'localhost', 'pool': {'size': 5}}, 'features': ['search']}, {'db': {'pool': {'size': 20}}, 'features': ['search', 'reviews']})returns{'db': {'host': 'localhost', 'pool': {'size': 20}}, 'features': ['search', 'reviews']}
callmerge_config({'a': 1}, {'b': 2})returns{'a': 1, 'b': 2}
callmerge_config({'log': {'level': 'INFO'}}, {})returns{'log': {'level': 'INFO'}}

Loading your progress…

Merge configuration layers without sharing anything — Python practice · Runtime