Created
January 14, 2023 23:15
-
-
Save brettvitaz/d1a29208b9930d87a85357ec80463dbc to your computer and use it in GitHub Desktop.
An "interesting" approach to dicts with dot notation
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
from typing import Union | |
import json | |
class AppSettings(dict): | |
def __init__(self, settings_filename): | |
self._settings_filename = settings_filename | |
with open(settings_filename, "r") as settings_file: | |
super().__init__(json.load(settings_file)) | |
def read(self, settings_filename=None): | |
self.clear() | |
settings_filename = settings_filename or self._settings_filename | |
with open(settings_filename, "r") as settings_file: | |
self.update(json.load(settings_file)) | |
def write(self, settings_filename=None): | |
settings_filename = settings_filename or self._settings_filename | |
with open(settings_filename, "w") as settings_file: | |
json.dump(self, settings_file, indent=2) | |
@classmethod | |
def _get_path(cls, result: Union[dict, list], path: list, idx=0): | |
if idx >= len(path): | |
return result | |
if type(result) is list: | |
new_result = result[int(path[idx])] | |
else: | |
new_result = result[path[idx]] | |
return cls._get_path(new_result, path, idx + 1) | |
def get_path(self, path, default=None): | |
path_split = path.split(".") | |
try: | |
return self._get_path(self, path_split) | |
except: | |
return default | |
@classmethod | |
def _set_path(cls, result: dict, path: list, value, idx=0): | |
if idx >= len(path) - 1: | |
result[path[idx]] = value | |
return result | |
try: | |
new_result = result[path[idx]] | |
except: | |
result.setdefault(path[idx], {}) | |
new_result = result[path[idx]] | |
return cls._set_path(new_result, path, value, idx + 1) | |
def set_path(self, path, value): | |
path_split = path.split(".") | |
self._set_path(self, path_split, value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment