class attrdict

Andrew Coffman pragmatic.python at gmail.com
Sat Mar 3 12:58:31 EST 2007


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.

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.

- Andrew Coffman


Alex Martelli wrote:
> MonkeeSage <MonkeeSage at gmail.com> wrote:
> 
> 
>>On Mar 2, 9:25 pm, a... at mac.com (Alex Martelli) wrote:
>>
>>>The problem is mostly that, given an instance a of attrdict, whether you
>>>can call (e.g.) a.update(foo) depends on whether you ever set
>>>a['update'], making the whole program extremely fragile -- a very high
>>>price to pay for some modest amount of syntax sugar.
>>
>>How about something like...
>>
>>class attrdict(dict):
>>    def __init__(self, *args, **kwargs):
>>        dict.__init__(self, *args, **kwargs)
>>        for k, v in self.items():
>>            dict.__setattr__(self, str(k), v)
>>    def __setitem__(self, k, v):
>>        dict.__setitem__(self, k, v)
>>        dict.__setattr__(self, str(k), v)
>>    __setattr__ = __setitem__
> 
> 
> Same problem: after x=attrdict(), x.update(foo) will work for a while,
> then suddenly stop working after some innocuous loop such as:
>     for bah in yech: x[bah] = 23
> when one of the items in yech just happens to be the word 'update'
> (similar issues with words such as 'get', 'pop', 'clear', etc, etc).
> 
> Miscegenation between attributes and items *inevitably* sucks.
> 
> 
> Alex



More information about the Python-list mailing list