Last active
March 13, 2017 14:19
-
-
Save jdiez17/b2ce86f857a920e7e25f9b5d40962cbc to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
class Config: | |
def __init__(self): | |
self._path = None | |
self._config = {} | |
def open(self, path): | |
self._path = path | |
try: | |
with open(path, "r") as f: | |
self._config = json.loads(f.read()) | |
except FileNotFoundError: | |
pass | |
def save(self): | |
if not self._path: | |
return | |
data = json.dumps(self._config, indent=4, sort_keys=True) | |
with open(self._path, "w") as f: | |
f.write(data) | |
def get(self, key, default=None): | |
d = self._config | |
path = key.split("/") | |
for entry in path: | |
d = d.get(entry) | |
if d is None: | |
self.set(key, default) | |
return default | |
return d | |
def set(self, key, value): | |
d = self._config | |
path = key.split("/") | |
for i, entry in enumerate(path): | |
if i == len(path) - 1: | |
d[entry] = value | |
break | |
if entry not in d: | |
d[entry] = {} | |
d = d.get(entry) | |
self.save() | |
config = Config() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment