class attrdict

MonkeeSage MonkeeSage at gmail.com
Fri Mar 2 23:23:54 EST 2007


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__

Regards,
Jordan




More information about the Python-list mailing list