Patching classes in Python
-
12-09-2019 - |
Question
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 )
Solution
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.)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow