deepmerge is a Python library providing a toolset for deeply merging Python dictionaries, handling nested structures, lists, and various data types with configurable strategies. The current stable version is 2.0, released recently with Python 3.8+ support. The library maintains a stable API, with new versions focusing on type hints, bug fixes, and minor enhancements.
pip install deepmergeVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to use the default `always_merger` to combine two dictionaries. Nested dictionaries are merged recursively, and lists are extended by default (elements from the second list are appended to the first). It's crucial to understand that `always_merger.merge(a, b)` modifies `a` in-place, so passing `{}`, `copy.copy(a)`, or `copy.deepcopy(a)` as the first argument is often necessary to prevent unintended side effects on the original dictionary.
Upgrade your Python environment to 3.8+ or pin `deepmerge` to a version prior to 2.0 (e.g., `pip install 'deepmerge<2.0'`).
Review any custom merge strategies or type-sensitive code after upgrading. Ensure your custom strategies correctly handle expected input and output types according to the new type hints.
Always pass a fresh dictionary (`{}`) or a deep copy (`copy.deepcopy(original_dict)`) as the first argument if the original dictionary must remain unchanged.To replace lists, initialize `Merger` with an 'override' strategy for lists: `my_merger = Merger([(list, ['override'])])`. To customize further, define your own list strategy function.
To merge multiple dictionaries, chain calls to `merge` or perform merges iteratively. For example, to merge `dict1` and `dict2` into a new dictionary: `merged_dict = always_merger.merge(always_merger.merge({}, dict1), dict2)`.To use `deepmerge`, you must import a `Merger` instance (like `always_merger`) or create your own `Merger` object and then call its `.merge()` method. Example: `from deepmerge import always_merger; result = always_merger.merge(base_dict, incoming_dict)`.
After creating a `Merger` instance (e.g., `my_merger = Merger(...)`), you need to invoke its `merge` method with the dictionaries you want to merge: `my_merger.merge(base_dict, incoming_dict)`.
When initializing the `Merger` class, provide explicit strategies for handling different data types and type conflicts. For example: `my_merger = Merger([(list, ['append']), (dict, ['merge'])], ['override'], ['override'])` where the last list `['override']` handles type conflicts. This ensures that a rule exists for all merging scenarios.