Fabric has a really nice, minimal implementation. Extending that to allow for nested access, we can use a defaultdict
, and the result looks something like this:
from collections import defaultdictclass AttributeDict(defaultdict): def __init__(self): super(AttributeDict, self).__init__(AttributeDict) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(key) def __setattr__(self, key, value): self[key] = value
Make use of it as follows:
keys = AttributeDict()keys.abc.xyz.x = 123keys.abc.xyz.a.b.c = 234
That elaborates a bit on Kugel's answer of "Derive from dict and and implement __getattr__
and __setattr__
". Now you know how!