Skip to content

Instantly share code, notes, and snippets.

@nadya-p
Last active May 10, 2026 15:03
Show Gist options
  • Select an option

  • Save nadya-p/b25519cf3a74d1bed86ed9b1d8c71692 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

Nice trick!

@bmoniey

bmoniey commented Jan 26, 2021

Copy link
Copy Markdown

Super clean, very nice!

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