>
>
> 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)
_______________________________________________
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com