Quantcast
Channel: How to use a dot "." to access members of dictionary? - Stack Overflow
Viewing all articles
Browse latest Browse all 40

Answer by Dave for How to use a dot "." to access members of dictionary?

$
0
0

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!


Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>