""" Creates a json file to store local data for tools Author: David Vega """ import os import json class Settings(object): """ Class that interfaces with the json file that stores settings""" def __init__(self, module=None, directory=None): self._path = None if not module and directory: self._path = directory elif module: self._path = os.path.dirname(module.__file__) else: raise Exception, "No module or directory provided" self._path = os.path.join(directory, "settings.json") self.LoadSettings() def __setattr__(self, key, value): """ Overrides built in setattr method. Saves out values set to the class whenever a new value is set Argument: key (string): name of the variable that you want to query value (object): value to store """ super(Settings, self).__setattr__(key, value) if key != "_path": self.SaveSettings() def Get(self, key, default=None): """ Gets an attribute and sets a default value for it if it isn't Argument: key (string): name of the variable that you want to query default (object): default value for the variable if it isn't found """ value = getattr(self, key, default) setattr(self, key, value) return value def LoadSettings(self): """ Loads the settings from the settings file """ if not os.path.exists(self._path): self.SaveSettings() with open(self._path, "r+") as settings: try: self.__dict__.update(json.load(settings)) except ValueError: self.SaveSettings() def SaveSettings(self): """ Saves out the internal data of the instance out to a json file """ # We don't need to store the path variable # So we create a new dictionary instance and remove it data = dict(self.__dict__) data.pop("_path") with open(self._path, "w") as settings: json.dump(data, settings, indent=4, separators=(',', ': '))