Created
January 13, 2021 13:02
-
-
Save jn0/ce4f025a98a1610cedfcf08c16f76038 to your computer and use it in GitHub Desktop.
DottedDict replacement
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
#!/usr/bin/env python3 | |
''' | |
Simple dict with dot-syntax access to its data. | |
Mostly for configs (the keys are already known). | |
Example: | |
cfg = DottedDict().load_json('config.json') | |
print(cfg.application.db.name) | |
''' | |
from collections import UserDict | |
import json | |
class DottedDict(UserDict): | |
def __getattr__(self, name): | |
return self.data[name] | |
def _set(self, dct): | |
self.clear() | |
self.update(dct) | |
return self | |
def from_json(self, text): | |
return self._set(json.loads(text, object_hook=self.__class__)) | |
def load_json(self, source): | |
if hasattr(source, 'read'): | |
return self._set(json.load(source, object_hook=self.__class__)) | |
if isinstance(source, str): | |
with open(source) as fp: | |
return self._set(json.load(fp, object_hook=self.__class__)) | |
raise NotImplementedError(f'Cannot load JSON from {source!r} of {type(source)!r}') | |
def __str__(self): | |
return json.dumps(self.data, | |
indent=2, | |
ensure_ascii=False, | |
default=lambda o: o.data if isinstance(o, UserDict) else o) | |
# vim:set ft=python ai et ts=4 sts=4 sw=4 cc=80:EOF # |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment