Created
May 16, 2019 22:20
-
-
Save gene1wood/d88f53f6f22517ac5659b8697d0ef075 to your computer and use it in GitHub Desktop.
Python dict object which persists its contents to disk with every change, either in JSON or YAML
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
import collections, json | |
class PersistedJSONDict(collections.MutableMapping): | |
def __init__(self, filename, *args, **kwargs): | |
self.filename = filename | |
self.store = dict() | |
self.load() | |
self.update(dict(*args, **kwargs)) | |
def __setitem__(self, key, value): | |
self.store[key] = value | |
self.save() | |
def __delitem__(self, key): | |
del self.store[key] | |
self.save() | |
def __getitem__(self, key): | |
return self.store[key] | |
def __iter__(self): | |
return iter(self.store) | |
def __len__(self): | |
return len(self.store) | |
def save(self): | |
with open(self.filename, 'w') as f: | |
json.dump(dict(self), f) | |
def load(self): | |
try: | |
with open(self.filename) as f: | |
self.update(**json.load(f)) | |
except: | |
pass | |
import collections, yaml | |
class PersistedYAMLDict(collections.MutableMapping): | |
def __init__(self, filename, *args, **kwargs): | |
self.filename = filename | |
self.store = dict() | |
self.load() | |
self.update(dict(*args, **kwargs)) | |
def __setitem__(self, key, value): | |
self.store[key] = value | |
self.save() | |
def __delitem__(self, key): | |
del self.store[key] | |
self.save() | |
def __getitem__(self, key): | |
return self.store[key] | |
def __iter__(self): | |
return iter(self.store) | |
def __len__(self): | |
return len(self.store) | |
def save(self): | |
with open(self.filename, 'w') as f: | |
f.write(yaml.dump(dict(self), default_flow_style=False)) | |
def load(self): | |
try: | |
with open(self.filename) as f: | |
self.update(**yaml.load(f.read())) | |
except: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment