#!/usr/bin/python3 import json class DictFile: """ This class is not safe to use! Any code in the file will be executed! """ def __init__(self, path: str=None): self.path = path if path is None: # create empty settings dict if path is none else load settings from file self.settings = {} else: self.load_from_file(path) def load_from_file(self, path): file = open(path, "r") self.settings = eval(file.read()) file.close() def save(self, path: str=None): if path is None: path = self.path file = open(path, "w") file.write(str(self)) file.close() def __str__(self): # make the dict not be just one line new_settings_str = "{\n" for key in self.settings: new_settings_str += "\t" + repr(key) + ": " + repr(self.settings[key]) + ",\n" new_settings_str = new_settings_str[:-2] + "\n}" return new_settings_str def __repr__(self): return repr(self.settings) def __getitem__(self, key): return self.settings[key] def __setitem__(self, key, value): self.settings[key] = value def __delitem__(self, key): self.settings.pop(key) def __iter__(self): return self.settings def __len__(self): return len(self.settings) class DataclassJSONFile: def __init__(self, file_path, dataclass, class_instance=None): self.file_path = file_path self.dataclass = dataclass self.class_instance = class_instance if class_instance is None: # load the class instance from the file if it is None self.load_from_file(file_path) def load_from_file(self, file_path): file = open(file_path, "r") class_dict = json.load(file) file.close() self.class_instance = self.dataclass(**class_dict) def save_to_file(self): class_dict = self.class_instance.__dict__ file = open(self.file_path, "w") json.dump(class_dict, file) file.close() def __repr__(self): return repr(self.class_instance) def __getitem__(self, key): return getattr(self.class_instance, key) def __setitem__(self, key, value): setattr(self.class_instance, key, value) def __delitem__(self, key): delattr(self.class_instance, key) def __iter__(self): return self.class_instance.__iter__() def __len__(self): return len(self.class_instance.__dict__) # these 2 functions do the exact same thing as in the class above def load_dataclass_json(dataclass, file_path: str): file = open(file_path, "r") class_dict = json.load(file) file.close() return dataclass(**class_dict) def save_dataclass_json(class_instance, file_path: str): class_dict = class_instance.__dict__ file = open(file_path, "w") json.dump(class_dict, file) file.close()