After changing a value in a dict
i'd like to automatically save that dict
to a file. I already do the saving to file but how to detect the change and trigger the saving?
I'm using Python 3.7
After changing a value in a dict
i'd like to automatically save that dict
to a file. I already do the saving to file but how to detect the change and trigger the saving?
I'm using Python 3.7
One option is to do the file writing at all points in your code where the dict
is modified.
An alternative is to use custom methods with a decorator to make any changes to the dictionary. This would look something like:
import json
import functools
# decorator to save functions return value to a file.
def decorated_change(func):
@functools.wraps(func)
def wrap(*args, **kwargs):
f = func(*args, **kwargs)
with open('file.txt', 'w') as file:
file.write(json.dumps(f))
return wrap
@decorated_change
def set_dict_entry(dict, key, value):
dict[key] = value
Ideally you would create your own dictionary class, and apply a similar decorator to the setitem method like so:
class modified_dict(dict):
@some_decorator
def __setitem__(self, i, y):
super().__setitem__
And additionally as others have pointed out you could simply forgo the decorator all together:
class modified_dict(dict):
def __setitem__(self, key, value):
super().__setitem__(key, value)
with open('file.txt', 'w') as f:
file.write(json.dumps(f, indent=4, sort_keys=True))
But if you plan on applying this type of mechanism on other data structures, it might be better to go with the decorator to adhere to DRY principles.