Browse Source

add AttributeDict

Nick Sweeting 5 years ago
parent
commit
dfb83b4f27
1 changed files with 17 additions and 0 deletions
  1. 17 0
      archivebox/util.py

+ 17 - 0
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