[Python-Dev] Dict access with double-dot (syntactic sugar)

Jameson Quinn jameson.quinn at gmail.com
Thu Mar 24 23:14:09 CET 2011


>
>
> 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>


More information about the Python-Dev mailing list