Stefano Borini
Stefano Borini

Reputation: 143815

Monkey patching a module function depending on another function inside the module

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?

Upvotes: 3

Views: 2897

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122392

You can just reference the dependency in your new function:

import broken

def brokenfunc():
    print "patched"

    broken.dependency()

broken.brokenfunc = brokenfunc

or you can add dependency to your module globals by import:

import broken
from broken import dependency

def brokenfunc():
    print "patched"

    dependency()

broken.brokenfunc = brokenfunc

There is really no need to go to such lengths; brokenfunc.__globals__ is just your current module namespace.

Upvotes: 4

Related Questions