Skip to content

Commit

Permalink
Add deep_update from pydantic
Browse files Browse the repository at this point in the history
  • Loading branch information
ZedThree committed May 3, 2024
1 parent 240fad7 commit 2bc99b0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/epydeck/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,19 @@ def dumps(deck: dict) -> str:
fh = StringIO()
dump(deck, fh)
return fh.getvalue()


def deep_update(deck: dict, *deck_patches: dict) -> dict:
"""Update `deck` recursively (like `dict.update` without
clobbering the nested dicts)
Lightly adapted from pydantic, MIT licence
"""
updated_deck = deck.copy()
for deck_patch in deck_patches:
for k, v in deck_patch.items():
if k in updated_deck and isinstance(updated_deck[k], dict) and isinstance(v, dict):
updated_deck[k] = deep_update(updated_deck[k], v)
else:
updated_deck[k] = v
return updated_deck
41 changes: 41 additions & 0 deletions test/test_epydeck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import epydeck


def test_deep_update():
deck = {
"repeated_block": {
"first": {"name": "first", "a": 1, "b": 2, "c": 3},
"second": {"name": "second", "a": 4, "b": 5, "c": 6},
},
"block": {
"a": 1,
"b": 2.3,
"c": "electron",
"d": "10 * femto",
"e": False,
"f": True,
},
}

patch = {
"repeated_block": {"first": {"b": 7}},
"block": {"b": 7.8, "e": True, "d": "20 * femto"}}

expected = {
"repeated_block": {
"first": {"name": "first", "a": 1, "b": 7, "c": 3},
"second": {"name": "second", "a": 4, "b": 5, "c": 6},
},
"block": {
"a": 1,
"b": 7.8,
"c": "electron",
"d": "20 * femto",
"e": True,
"f": True,
},
}

result = epydeck.deep_update(deck, patch)

assert result == expected

0 comments on commit 2bc99b0

Please sign in to comment.