class attrdict

Alex Martelli aleax at mac.com
Sat Mar 3 14:29:42 EST 2007


Andrew Coffman <pragmatic.python at gmail.com> wrote:

> Could you do something like this?
> 
> class attrdict(dict):
>      def __getattr__(self, attr):
>          if self.has_key(attr):
>              return self[attr]
>          else:
>              message = "'attrdict' object has no attribute '%s'" % attr
>              raise AttributeError, message
> 
> If you have a dict item with the same name as a method in the class, you
> won't be able to get to it using syntax sugar, though.

Yes.  In __setattr__, you can choose what to do in that case (it doesn't
seem to make sense to be able to *assign* to foo.get without being able
to *access* as foo.get whatever you've assigned).

> It doesn't seem that the syntax sugar saves you much typing anyway 
> (a.foo vs. a['foo']), but perhaps it seems nicer in some aesthetic sense.

It would be nice, yes, weren't it for the inevitable irregularity, one
way or another, caused by the clash between attributes and items.

If, instead of subclassing dict, one wrapped it (and properly coded just
a few specialmethods, no ordinary ones), the overall effect could be
more regular (probably still with some limitation, since the dict does
need to be kept somewhere, and keys clashing with the special methods'
names would still have to be forbidden or otherwise specialcased).


Alex



More information about the Python-list mailing list