"Extracting" a dictionary

Noldoaran RobbTiger at softhome.net
Thu May 20 12:18:07 EDT 2004


Arnold Filip:
> How about this:
> 
> In [1]: d = {'foo' : 23, 'bar' : 42}
> 
> In [2]: for item in d.items():
>     ...:         exec "%s = %d" % item
>     ...:
> 
> In [3]: foo
> Out[3]: 23
> 
> In [4]: bar
> Out[4]: 42

you could extract them in to there own namespace:
>>> class AttrDict:
...     def __init__(self, d):
...         self.__d = d
...     def __getattr__(self,attr):
...         return self.__d[attr]
...     def __setattr__(self,attr,value):
...         self.__d[attr] = value
...     def __delattr__(self,attr):
...         del self.__d[attr]
...
>>> d = AttrDict({'foo' : 23, 'bar' : 42})
Traceback (most recent call last):
  File "<input>", line 1, in ?
  File "<input>", line 3, in __init__
  File "<input>", line 10, in __setattr__
(snip)
RuntimeError: maximum recursion depth exceeded
>>> d.foo

That didn't work like I hoped. I decided to share it anyway in case
someone can get it to work.

--Noldoaran



More information about the Python-list mailing list