Last active
June 12, 2024 19:39
-
-
Save nadya-p/b25519cf3a74d1bed86ed9b1d8c71692 to your computer and use it in GitHub Desktop.
Simple Python settings class using JSON file as storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Nice trick!