Skip to content

Instantly share code, notes, and snippets.

@nadya-p
Last active March 8, 2024 07:34
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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'
@Zeebrommer
Copy link

Nice trick!

@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