class attrdict

MonkeeSage MonkeeSage at
Sat Mar 3 05:23:54 CET 2007

On Mar 2, 9:25 pm, a... at (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__


More information about the Python-list mailing list