Last active
September 2, 2019 09:47
-
-
Save SteadBytes/b3f3e05c02df13d7526d8f6638e27d6b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
from typing import Iterable | |
def dict_values_same_types(key, cls, *dicts): | |
return all(isinstance(d[key], cls) for d in dicts) | |
def dict_merger(original: dict, incoming: dict): | |
""" | |
In place deep merge `incoming` into `original`. | |
**You probably want `merge_dicts`, this is a lower-level function used by it** | |
Key conflict bevaviour: | |
- `dict`: Recursively call dict_merger on both values | |
- `int`: sum values | |
- any other type: Override value in `original` with value in `incoming | |
If values of same key have conflicting *type*, value in `original` overridden. | |
""" | |
def type_match(key, cls): | |
return dict_values_same_types(key, cls, original, incoming) | |
for key in incoming: | |
if key in original: | |
if type_match(key, dict): | |
dict_merger(original[key], incoming[key]) | |
# isinstance(True, int) == True, isinstance(1, bool) == False | |
elif type_match(key, int) and not type_match(key, bool): | |
original[key] += incoming[key] | |
else: | |
original[key] = incoming[key] | |
else: | |
original[key] = incoming[key] | |
return original | |
def merge_dicts(*dicts: Iterable[dict]): | |
""" | |
Deep merge `dicts` into a single new dict. **Warning**: this will modify | |
`dicts` due to in place updates. | |
""" | |
return reduce(dict_merger, dicts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO:
int
's should be multiplied instead of added orstr
s should be concatenated instead of overwritten e.t.c