Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A class with persistent data
import json
import os
import pickle
import random
import uuid
class PersistentClass:
reserved_keys = ["__dict__", "filename", "debug", "autosave", "file_ext"]
def __init__(self, unique_tag=None, autosave=True, file_ext="json"):
self.autosave = autosave
self.file_ext = file_ext.lower()
self.debug = True
name = type(self).__name__
if unique_tag:
name = f"{name}_{unique_tag}"
self.filename = f"db{os.sep}{name}.{self.file_ext}"
folder = os.sep.join(self.filename.split(os.sep)[:-1])
if not os.path.exists(folder):
os.makedirs(folder)
self.load()
def load(self):
open_type = "r" if self.file_ext == "json" else "rb"
if os.path.exists(self.filename):
with open(self.filename, open_type) as f:
d = {}
if self.file_ext == "json":
d = json.load(f)
else:
d = pickle.load(f)
for a in d:
self.__dict__[a] = d[a]
def save(self):
open_type = "w" if self.file_ext == "json" else "wb"
with open(self.filename, open_type) as outfile:
if self.file_ext == "json":
json.dump(self.get_dict(), outfile)
else:
pickle.dump(self.get_dict(), outfile)
def __setattr__(self, key, value):
if key not in self.__dict__ or self.__dict__[key] != value:
self.__dict__[key] = value
if self.autosave and key not in PersistentClass.reserved_keys:
self.save()
def __delattr__(self, item):
if item not in PersistentClass.reserved_keys:
del self.__dict__[item]
if self.autosave:
self.save()
def __getattr__(self, item):
return self.__dict__[item] if item in self.__dict__ else None
def get_dict(self):
d = self.__dict__
return {a: d[a] for a in d if a not in PersistentClass.reserved_keys}
def __str__(self):
return json.dumps(self.get_dict(), indent=4)
def clear(self):
keys = [a for a in self.__dict__ if a not in PersistentClass.reserved_keys]
for a in keys:
del self.__dict__[a]
if os.path.exists(self.filename):
os.remove(self.filename)
def __enter__(self):
self.autosave = False
def __exit__(self, exc_type, exc_val, exc_tb):
self.save()
self.autosave = True
if __name__ == "__main__":
types = ["json", "pkl"]
temp_data = {f"s_{a}_{b}_{uuid.uuid4()}": str(uuid.uuid4()) for a in str(uuid.uuid4()) for b in range(10)}
temp_data.update({f"n_{a}_{b}_{uuid.uuid4()}": random.random() for a in str(uuid.uuid4()) for b in range(10)})
for t in types:
print("\n", t)
my_file = PersistentClass(file_ext=t)
print(str(my_file))
my_file.clear()
print(str(my_file))
with my_file:
my_file.my_var = "accepts variable assignment"
for a in temp_data:
setattr(my_file, a, temp_data[a])
print(str(my_file))
my_file.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment