Skip to main content

A deep merge function for 🐍.

Project description

mergedeep

PyPi release PyPi versions Downloads Documentation Status

A deep merge function for 🐍.

Check out the mergedeep docs

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:

  1. 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 with 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]}
  1. Additive
# Strategy.ADDITIVE
# When `target` and `source` values are both either `list` 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]}
  1. Typesafe
# Strategy.TYPESAFE
# When `target` and `source` values are of different types, raise `TypeError`.

from mergedeep import merge, Strategy

target = {"key": [1, 2]}
source = {"key": {3, 4}}

merge(target, source, strategy=Strategy.TYPESAFE) 
# TypeError: target type: <class 'list'> differs from source type: <class 'set'> for key: "key"

License

MIT © Travis Clarke

Project details


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.0.3.tar.gz (3.9 kB view hashes)

Uploaded Source

Built Distribution

mergedeep-1.0.3-py3-none-any.whl (5.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page