class attrdict
goodwolf
Robert.Katic at gmail.com
Sun Mar 4 08:24:25 EST 2007
On Mar 4, 1:03 pm, "goodwolf" <Robert.Ka... at gmail.com> wrote:
> 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
oops, there is an error (empty dict is created once).
Here corrected one:
class Namespace(object):
def __init__(self, __ns=None, **kwargs):
if __ns is None:
self.__dict__ = kwargs
else:
assert len(kwargs) == 0
self.__dict__ = __ns
If you are familiar with JS then you can simulate JS Object:
class JSLikeObject(object):
def __init__(self, __ns={}, **kwargs):
if kwargs: __ns.update(kwargs)
self.__dict__ = __ns
def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
setattr(self, name, value)
def __delitem__(self, name):
delattr(self, name)
def __iter__(self):
return iter(self.__dict__)
def __contains__(self, name):
return hasattr(self, name)
but I don't sagest to use it in real life.
More information about the Python-list
mailing list