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

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

$
0
0

I ended up trying BOTH the AttrDict and the Bunch libraries and found them to be way to slow for my uses. After a friend and I looked into it, we found that the main method for writing these libraries results in the library aggressively recursing through a nested object and making copies of the dictionary object throughout. With this in mind, we made two key changes. 1) We made attributes lazy-loaded 2) instead of creating copies of a dictionary object, we create copies of a light-weight proxy object. This is the final implementation. The performance increase of using this code is incredible. When using AttrDict or Bunch, these two libraries alone consumed 1/2 and 1/3 respectively of my request time(what!?). This code reduced that time to almost nothing(somewhere in the range of 0.5ms). This of course depends on your needs, but if you are using this functionality quite a bit in your code, definitely go with something simple like this.

class DictProxy(object):    def __init__(self, obj):        self.obj = obj    def __getitem__(self, key):        return wrap(self.obj[key])    def __getattr__(self, key):        try:            return wrap(getattr(self.obj, key))        except AttributeError:            try:                return self[key]            except KeyError:                raise AttributeError(key)    # you probably also want to proxy important list properties along like    # items(), iteritems() and __len__class ListProxy(object):    def __init__(self, obj):        self.obj = obj    def __getitem__(self, key):        return wrap(self.obj[key])    # you probably also want to proxy important list properties along like    # __iter__ and __len__def wrap(value):    if isinstance(value, dict):        return DictProxy(value)    if isinstance(value, (tuple, list)):        return ListProxy(value)    return value

See the original implementation here by https://stackoverflow.com/users/704327/michael-merickel.

The other thing to note, is that this implementation is pretty simple and doesn't implement all of the methods you might need. You'll need to write those as required on the DictProxy or ListProxy objects.


Viewing all articles
Browse latest Browse all 40

Trending Articles



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