views:

239

answers:

1

Suppose I have a Python class that I want to add an extra property to.

Is there any difference between

import path.MyClass
MyClass.foo = bar

and using something like :

import path.MyClass
setattr(MyClass, 'foo', bar)

?

If not, why do people seem to do the second rather than the first? (Eg. here http://concisionandconcinnity.blogspot.com/2008/10/chaining-monkey-patches-in-python.html )

+8  A: 

The statements are equivalent, but setattr might be used because it's the most dynamic choice of the two (with setattr you can use a variable for the attribute name.)

See: http://docs.python.org/library/functions.html#setattr

Blixt
Agreed. In particular, this would be required the way patching was performed in the OP's referred-to blog entry - the name of the method was not known by the innards of the monkeypatch method.
Blair Conrad
thanks. But I updated the question because I still don't see that one is more dynamic than the other
interstar
ah ... no, I see what you mean ... sorry .. doh!
interstar