"Extracting" a dictionary
Noldoaran
RobbTiger at softhome.net
Fri May 21 11:40:43 EDT 2004
Peter Otten:
> Saying self.__d = dont_care invokes __setattr__() to set __d, __setattr__()
> asks __getattr__() for __d, which asks __getattr__() for __d to determine
> __d ...ad infinitum.
> To avoid the recursion you must bypass __setattr__() by accessing __dict__
> directly.
(snip)
> While this works, you can achieve the same functionality in a more elegant
> way:
>
> >>> class AttrDict:
> ... def __init__(self, d):
> ... self.__dict__.update(d)
> ...
(snip)
> A standard trick, by the way. Can't think of the right google keywords right
> now, so I use another standard trick and leave finding them as an excercise
> to the reader :-)
>
> Peter
Thanks, Peter. I found another way that also works:
>>> class AttrDict(dict):
... __getattr__ = dict.__getitem__
... __getattribute__ = __getattr__
... __setattr__ = dict.__setitem__
... __delattr__ = dict.__delitem__
...
>>> d = AttrDict({'foo': 23, 'bar': 42})
>>> d.foo
23
>>> d.bar
42
>>> d.spam = 123
>>> d.spam
123
>>> d
{'spam': 123, 'foo': 23, 'bar': 42}
----
~Noldoaran
More information about the Python-list
mailing list