> > > You're correct, this is trivial with object_hook. > > >>> class AttrDict(dict): > ... def __getattr__(self, attr): > ... try: > ... return self[attr] > ... except KeyError: > ... raise AttributeError(attr) > ... > >>> import json > >>> obj = json.loads('{"foo": {"bar": "baz"}}', object_hook=AttrDict) > {u'foo': {u'bar': u'baz'}} > >>> obj.foo.bar > u'baz' > > -bob > That's pretty good, but it does clone the dict unnecessarily. I prefer: class AttrDict(object): def __init__(self, adict): self.__dict__ = adict #a reference, not a copy def __getattr__(self, attr): if hasattr(dict, attr): #built-in methods of dict... return getattr(self.__dict__, attr) #...are bound directly to the dict else: try: return self.__dict__[attr] except KeyError: raise AttributeError(attr) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20110324/6efdc0bf/attachment.html>
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4