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 )
Vinko Vrsalovic
342k55 gold badges341 silver badges374 bronze badges
asked Jun 8, 2009 at 11:53
interstar
27.5k38 gold badges120 silver badges188 bronze badges
-
1Why not update you class's definition with the additional method? Why do all this "magical" stuff when you can simply edit the class definition?S.Lott– S.Lott2009年06月08日 12:28:23 +00:00Commented Jun 8, 2009 at 12:28
-
In my particular problem when I asked this, the class came from a library that we didn't want to change; and we couldn't subclass it. Though agree in general.interstar– interstar2009年06月09日 09:50:58 +00:00Commented Jun 9, 2009 at 9:50
1 Answer 1
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.)
answered Jun 8, 2009 at 11:57
Blixt
50.3k13 gold badges128 silver badges155 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Blair Conrad
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.
interstar
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!
lang-py