Skip to content

Instantly share code, notes, and snippets.

@xaviergoby
Forked from nadya-p/settings.py
Created December 27, 2018 03:37
Show Gist options
  • Save xaviergoby/a23edddc20894ae5ff3c278e7488dfd3 to your computer and use it in GitHub Desktop.
Save xaviergoby/a23edddc20894ae5ff3c278e7488dfd3 to your computer and use it in GitHub Desktop.
Simple Python settings class using JSON file as storage
import json
import os
class Settings:
_config_location = 'config.json'
def __init__(self):
if os.path.exists(self._config_location):
self.__dict__ = json.load(open(self._config_location))
else:
self.__dict__ = {
'settingA': 'myDefaultSettingA',
'settingB': 'myDefaultSettingB'
}
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
json.dump(self.__dict__, open(self._config_location, 'w'))
if __name__ == "__main__":
with Settings() as settings: # Those settings will be saved (with eventual modifications) when script exits
settings.settingA = 'myNewSettingA'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment