Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patching classes in Python

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 )

like image 653
interstar Avatar asked Jun 08 '09 11:06

interstar


People also ask

What does patches do in Python?

patch() unittest. mock provides a powerful mechanism for mocking objects, called patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.

What is difference between mock and patch?

Patching vs Mocking: Patching a function is adjusting it's functionality. In the context of unit testing we patch a dependency away; so we replace the dependency. Mocking is imitating. Usually we patch a function to use a mock we control instead of a dependency we don't control.

What is Python Unittest patch?

unittest. mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest.


1 Answers

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

like image 151
Blixt Avatar answered Sep 28 '22 04:09

Blixt