Python patch classes

Suppose I have a Python class for which I want to add an additional property.

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 be doing the second, not the first? (For example, here http://concisionandconcinnity.blogspot.com/2008/10/chaining-monkey-patches-in-python.html )

+6
python class monkeypatching
source share
1 answer

The operators are equivalent, but setattr can be used because it is the most dynamic choice of two (using setattr you can use a variable for the attribute name.)

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

+11
source share

All Articles