Skip to content

Instantly share code, notes, and snippets.

@nadya-p
Last active June 12, 2024 19:39
Show Gist options
  • Save nadya-p/b25519cf3a74d1bed86ed9b1d8c71692 to your computer and use it in GitHub Desktop.
Save nadya-p/b25519cf3a74d1bed86ed9b1d8c71692 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'
@bmoniey
Copy link

bmoniey commented Jan 26, 2021

Super clean, very nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment