From 16c2f19ec5bdf47d3ac250dfae72a1406bbfa357 Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Sat, 18 Jan 2020 23:35:26 -0800 Subject: [PATCH] Allow getattr in loaded json configs --- amanuensis/config/loader.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/amanuensis/config/loader.py b/amanuensis/config/loader.py index b1d9df4..63d5d17 100644 --- a/amanuensis/config/loader.py +++ b/amanuensis/config/loader.py @@ -7,6 +7,20 @@ import os # Module imports from errors import ReadOnlyError + +class AttrOrderedDict(OrderedDict): + """An ordered dictionary with access via __getattr__""" + def __getattr__(self, key): + if key not in self: + raise AttributeError(key) + return self[key] + + def __setattr__(self, key, value): + if key not in self: + raise AttributeError(key) + self[key] = value + + class ReadOnlyOrderedDict(OrderedDict): """An ordered dictionary that cannot be modified""" def __readonly__(self, *args, **kwargs): @@ -22,6 +36,11 @@ class ReadOnlyOrderedDict(OrderedDict): self.update = self.__readonly__ self.setdefault = self.__readonly__ + def __getattr__(self, key): + if key not in self: + raise AttributeError(key) + return self[key] + class open_lock(): def __init__(self, path, mode, lock_type): self.fd = open(path, mode, encoding='utf8') @@ -57,7 +76,7 @@ class json_rw(open_ex): self.config = None def __enter__(self): - self.config = json.load(self.fd, object_pairs_hook=OrderedDict) + self.config = json.load(self.fd, object_pairs_hook=AttrOrderedDict) return self.config def __exit__(self, exc_type, exc_value, traceback):