class attrdict

goodwolf Robert.Katic at gmail.com
Sun Mar 4 07:03:26 EST 2007


On Mar 3, 4:25 am, a... at mac.com (Alex Martelli) wrote:
> Hallvard B Furuseth <h.b.furus... at usit.uio.no> wrote:
>
> > Does this class need anything more?
> > Is there any risk of a lookup loop?
> > Seems to work...
>
> > class attrdict(dict):
> >     """Dict where d['foo'] also can be accessed as d.foo"""
> >     def __init__(self, *args, **kwargs):
> >         self.__dict__ = self
> >         dict.__init__(self, *args, **kwargs)
> >     def __repr__(self):
> >         return dict.__repr__(self).join(("attrdict(", ")"))
>
> 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.
>
> Alex

Then you will prefer something like this:

class Namespace(object):
    def __init__(self, __ns={}, **kwargs):
        if kwargs: __ns.update(kwargs)
        self.__dict__ = __ns




More information about the Python-list mailing list