6

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
2
  • 1
    Why not update you class's definition with the additional method? Why do all this "magical" stuff when you can simply edit the class definition? Commented 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. Commented Jun 9, 2009 at 9:50

1 Answer 1

11

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

answered Jun 8, 2009 at 11:57
Sign up to request clarification or add additional context in comments.

3 Comments

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.
thanks. But I updated the question because I still don't see that one is more dynamic than the other
ah ... no, I see what you mean ... sorry .. doh!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.