how to monkey patch function_1 if function_1 is called by function_2

Question:

The code structure is basically like below. external_lib.py is an external library that I cannot modify, while my_module.py is the python file I own. I’ve written pseudo code in my_module.py for what I’m trying to accomplish.

external_lib.py

def function_1(arg1, arg2):
  # expensive calculations that generates output from arg1 and arg2
  ...
  return output

def function_2(arg1, arg2):
  ...
  return function_1(arg1, arg2)

my_module.py

import external_lib

def function_1(arg1, arg2):
  arg1 += '_'
  # do what the original external_lib.function_1 did

# this is probably wrong. it's my attempt at monkey patching
external_lib.function_1 = function_1

# I want this call to call the monkey patched function_1 via function_2
external_lib.function_2('a', 'b')

I’m basically stuck with two things:

  1. How to monkey patch a sub-level module-level function
  2. How to monkey path a function so that the new function adds an additional step to the original function.
Asked By: jencake

||

Answers:

I have tried your solution and it works for me.

stack2.py

def func1(a, b):
    return a + b


def func2(a, b):
    return func1(a, b)

stack.py

import stack2

def new_func_one(a, b):
    return 4


stack2.func1 = new_func_one
print(stack2.func2(1, 1))

This prints 4.

Additionally to fix problem no. 2:

import copy
import stack2


old_func1 = copy.deepcopy(stack2.func1)

def new_func_one(a, b):
    return old_func1(a, b) + 1

stack2.func1 = new_func_one

print(stack2.func2(1, 1))

This for example, adds an increment of 1 to the original implementation of the function.

Answered By: H.Syd
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.