Skip to content

Instantly share code, notes, and snippets.

@SteadBytes
Last active September 2, 2019 09:47
Show Gist options
  • Save SteadBytes/b3f3e05c02df13d7526d8f6638e27d6b to your computer and use it in GitHub Desktop.
Save SteadBytes/b3f3e05c02df13d7526d8f6638e27d6b to your computer and use it in GitHub Desktop.
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)
@SteadBytes
Copy link
Author

TODO:

  • Handle lists
    • Merge instead of overwriting
  • Allow 'merger' function for different types to be passed in to improve API
    • i.e. allow caller to specify that int's should be multiplied instead of added or strs should be concatenated instead of overwritten e.t.c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment