From 53c86c30a1a1590e323555954516ff0949bc0c9f Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Sat, 11 Aug 2018 18:19:55 -0700 Subject: [PATCH] Improve clarity of the recursive_dict_ helper functions & usage. --- etiquette/helpers.py | 20 +++++++++++++------- etiquette/photodb.py | 9 +++++++-- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/etiquette/helpers.py b/etiquette/helpers.py index 91a576b..99fbe89 100644 --- a/etiquette/helpers.py +++ b/etiquette/helpers.py @@ -325,7 +325,17 @@ def read_filebytes(filepath, range_min=0, range_max=None, chunk_size=bytestring. def recursive_dict_update(target, supply): ''' Update target using supply, but when the value is a dictionary update the - insides instead of replacing the dictionary itself. + insides instead of replacing the dictionary itself. This prevents keys that + exist in the target but don't exist in the supply from being erased. + Note that we are modifying target in place. + + eg: + target = {'hi': 'ho', 'neighbor': {'name': 'Wilson'}} + supply = {'neighbor': {'behind': 'fence'}} + + result: {'hi': 'ho', 'neighbor': {'name': 'Wilson', 'behind': 'fence'}} + whereas a regular dict.update would have produced: + {'hi': 'ho', 'neighbor': {'behind': 'fence'}} ''' for (key, value) in supply.items(): if isinstance(value, dict): @@ -333,7 +343,7 @@ def recursive_dict_update(target, supply): if existing is None: target[key] = value else: - recursive_dict_update(existing, value) + recursive_dict_update(target=existing, supply=value) else: target[key] = value @@ -343,11 +353,7 @@ def recursive_dict_keys(d): all other dictionaries that appear as values within. The subkeys will use \\ to indicate their lineage. - { - 'hi': { - 'ho': 'neighbor' - } - } + {'hi': {'ho': 'neighbor'}} returns diff --git a/etiquette/photodb.py b/etiquette/photodb.py index b3a7c34..8f41313 100644 --- a/etiquette/photodb.py +++ b/etiquette/photodb.py @@ -1530,9 +1530,14 @@ class PhotoDB( if user_config_exists: with open(self.config_filepath.absolute_path, 'r', encoding='utf-8') as handle: user_config = json.load(handle) - my_keys = helpers.recursive_dict_keys(config) + + # If the default config has been updated and contains new keys, + # then they will not yet exist in the user's config, and we should + # save the file after giving it those default values. + default_keys = helpers.recursive_dict_keys(config) stored_keys = helpers.recursive_dict_keys(user_config) - needs_dump = not my_keys.issubset(stored_keys) + needs_dump = default_keys > stored_keys + helpers.recursive_dict_update(target=config, supply=user_config) else: needs_dump = True