__dict__ is neato torpedo!

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jun 11 22:13:11 EDT 2011


On Sat, 11 Jun 2011 20:32:37 -0500, Andrew Berg wrote:

> I'm pretty happy that I can copy variables and their value from one
> object's namespace to another object's namespace with the same variable
> names automatically:
> 
> class simpleObject():
>     pass
> 
> a = simpleObject()
> b = simpleObject()
> 
> a.val1 = 1
> a.val2 = 2
> b.__dict__.update(a.__dict__)
[...]


> The reason I'm posting this is to ask what to watch out for when doing
> this. I've seen vague warnings that I don't really understand, and I'm
> hoping someone can enlighten me.

You are injecting data and code from one object to another. If you don't 
know what you're injecting, bad things could happen. Just like in real 
life :)

The update method unconditionally replaces any item in the first object 
that matches an item in the second. If it has things you don't want, too 
bad, you'll get them:


>>> class K(object):
...     data = "things"
...     status = "working hard for a living"
...
>>> a = K()
>>> b = K()
>>> b.data = "stuff and things"  # what you want
>>> b.status = "leaching off dear old granny"  # but not this one
>>>
>>> a.__dict__.update(b.__dict__)
>>> print(a.status)
leaching off dear old granny


So never update from a random object you don't know well.

A second, more subtle risk: not all objects have a __dict__. But if you 
obey the rule about never updating from arbitrary objects you don't know, 
then you won't be surprised by an object with no __dict__.

Other than that, using update is a good trick to have in your toolbox.




-- 
Steven



More information about the Python-list mailing list