Jonathan Livni
Jonathan Livni

Reputation: 107092

patching a local instance

consider I have the following code in python module a.py:

def func():
    obj = Obj()
    # Some code that uses obj

Is there a way to monkey patch obj without making it a function argument?

Reason: In the context of the code itself it should not be an argument, however in the context of testing and system simulations using the code, the patch is reasonable. Also in various scenarios I may need to patch different local objects and placing all of them as arguments would be tedious.

Upvotes: 1

Views: 81

Answers (1)

jfs
jfs

Reputation: 414207

# if func() is defined in `a.py`
import a

oldObj, a.Obj = a.Obj, MockObj
a.func()
a.Obj = oldObj

Upvotes: 2

Related Questions