From dfb83b4f2728f2f0a389650836d6164a2f80e809 Mon Sep 17 00:00:00 2001 From: Nick Sweeting <git@sweeting.me> Date: Mon, 13 Jul 2020 11:24:49 -0400 Subject: [PATCH] add AttributeDict --- archivebox/util.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/archivebox/util.py b/archivebox/util.py index 8fdda389..0e7ebd31 100644 --- a/archivebox/util.py +++ b/archivebox/util.py @@ -230,6 +230,23 @@ def ansi_to_html(text): return COLOR_REGEX.sub(single_sub, text) +class AttributeDict(dict): + """Helper to allow accessing dict values via Example.key or Example['key']""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Recursively convert nested dicts to AttributeDicts (optional): + # for key, val in self.items(): + # if isinstance(val, dict) and type(val) is not AttributeDict: + # self[key] = AttributeDict(val) + + def __getattr__(self, attr: str) -> Any: + return dict.__getitem__(self, attr) + + def __setattr__(self, attr: str, value: Any) -> None: + return dict.__setitem__(self, attr, value) + + class ExtendedEncoder(pyjson.JSONEncoder): """ Extended json serializer that supports serializing several model