which "dictionary with attribute-style access"?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Oct 22 00:34:48 EDT 2009


En Wed, 21 Oct 2009 18:40:01 -0300, Andreas Balogh <baloand at gmail.com>  
escribió:

> Gabriel, thanks for your hint. I've managed to create an implementation  
> of an AttrDict passing Gabriels tests.
>
> Any more comments about the pythonicness of this implementation?
>
> class AttrDict(dict):
>      """A dict whose items can also be accessed as member variables."""
>      def __init__(self, *args, **kwargs):
>          dict.__init__(self, *args, **kwargs)
>          self.__dict__ = self
>
>      def copy(self):
>          return AttrDict(self)
>
>      def __repr__(self):
>          return 'AttrDict(' + dict.__repr__(self) + ')'
>
>      @classmethod
>      def fromkeys(self, seq, value = None):
>          return AttrDict(dict.fromkeys(seq, value))
>

Looks fine as long as nobody uses an existing method name as a dictionary  
key:

py> d = AttrDict({'name':'value'})
py> d.items()
[('name', 'value')]
py> d = AttrDict({'items': [1,2,3]})
py> d.items()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

(I should have included a test case for this issue too).
Of course, if this doesn't matter in your application, go ahead and use  
it. Just be aware of the problem.

-- 
Gabriel Genellina




More information about the Python-list mailing list