I have a function inside a module that is broken
broken.py
def brokenfunc():
dependency()
def dependency():
print "hello"
The routine depends on another function dependency, which is fine. I need to monkey patch broken, so in another module I did
patched.py
import broken
def brokenfunc():
print "patched"
dependency()
brokenfunc.__globals__["dependency"]=broken.brokenfunc.__globals__["dependency"]
broken.brokenfunc = brokenfunc
broken.brokenfunc()
Clearly, I have to override the globals because the dependency in the patched function is defined in the patched module and would look for dependency there.
This works, but I am unsatisfied with the hack. I tried to update the whole globals dictionary, but in that case I override too much and the broken function keeps runnning. Is this the correct way of doing it (considering also corner cases) or there's another, correct strategy?