Skip to content

Instantly share code, notes, and snippets.

@suvayu
Created December 4, 2020 02:44
Show Gist options
  • Save suvayu/fec82a7549274e3e579c68dfa8e90538 to your computer and use it in GitHub Desktop.
Save suvayu/fec82a7549274e3e579c68dfa8e90538 to your computer and use it in GitHub Desktop.
A minimal attribute dictionary implementation using `defaultdict`
from collections import defaultdict
class _attrdict(defaultdict):
__getattr__ = defaultdict.__getitem__
__setattr__ = defaultdict.__setitem__
def update(self, other):
super().update(
(k, v) for k, v in other.items() if not issubclass(type(v), dict)
)
for k, v in other.items():
if issubclass(type(v), dict):
if k not in self or not isinstance(self[k], type(self)):
self[k] = attrdict()
self[k].update(v)
def attrdict():
return _attrdict(attrdict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment