A deep merge function for 🐍.
Project description
mergedeep
A deep merge function for 🐍.
Installation
$ pip install mergedeep
Usage
merge(target: Map[KT, VT], *sources: Map[KT, VT], strategy: Strategy = Strategy.REPLACE) -> Map[KT, VT]
Deep merge without mutating the source dicts.
from mergedeep import merge
a = {"keyA": 1}
b = {"keyB": {"sub1": 10}}
c = {"keyB": {"sub2": 20}}
merged = merge({}, a, b, c)
print(merged)
# {"keyA": 1, "keyB": {"sub1": 10, "sub2": 20}}
Deep merge into an existing dict.
from mergedeep import merge
a = {"keyA": 1}
b = {"keyB": {"sub1": 10}}
c = {"keyB": {"sub2": 20}}
merge(a, b, c)
print(a)
# {"keyA": 1, "keyB": {"sub1": 10, "sub2": 20}}
Merge strategies:
- Replace (default)
# Strategy.REPLACE
# When `target` and `source` values are the same, replace the `target` value with one from `source` (default).
# Note: with multiple sources, the `last` source value will be what appears in the merged result.
from mergedeep import merge, Strategy
target = {"key": [1, 2]}
source = {"key": [3, 4]}
merge(target, source, strategy=Strategy.REPLACE)
# same as: merge(target, source)
print(target)
# {"key": [3, 4]}
- Additive
# Strategy.ADDITIVE
# When `target` and `source` values are both either `list`, `tuple`, or `set`, extend/update `target` with values from `source` collection.
from mergedeep import merge, Strategy
target = {"key": [1, 2]}
source = {"key": [3, 4]}
merge(target, source, strategy=Strategy.ADDITIVE)
print(target)
# {"key": [1, 2, 3, 4]}
- Typesafe replace
# Strategy.TYPESAFE_REPLACE or Strategy.TYPESAFE
# When `target` and `source` values are of different types, raise `TypeError`. Otherwise, perform a `REPLACE` merge.
from mergedeep import merge, Strategy
target = {"key": [1, 2]}
source = {"key": {3, 4}}
merge(target, source, strategy=Strategy.TYPESAFE_REPLACE) # or `Strategy.TYPESAFE`
# TypeError: target type: <class 'list'> differs from source type: <class 'set'> for key: "key"
- Typesafe additive
# Strategy.TYPESAFE_ADDITIVE
# When `target` and `source` values are of different types, raise `TypeError`. Otherwise, perform a `ADDITIVE` merge.
from mergedeep import merge, Strategy
target = {"key": [1, 2]}
source = {"key": {3, 4}}
merge(target, source, strategy=Strategy.TYPESAFE_ADDITIVE)
# TypeError: target type: <class 'list'> differs from source type: <class 'set'> for key: "key"
License
MIT © Travis Clarke
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
mergedeep-1.2.0.tar.gz
(4.4 kB
view hashes)
Built Distribution
Close
Hashes for mergedeep-1.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | faba4de8d632f00d6159f2e3b6078034aabca632c87d5c49d714d133d3cf9654 |
|
MD5 | 7316d223b2bf96315c61fe62be314d5b |
|
BLAKE2b-256 | f447ce49d70b7526bba75fe62cb2ff2a01d01e331683b30096c7dac0fce8bf8e |