5

I want to monkey patch on f(*args, **kwargs) from an installed module. I use the idea of decorator on my own code, but other methods from the installed module fails to call f correctly.

Here is an example:

import numpy as np
def log(func):
 def wrapper(*args, **kwargs):
 print('logging')
 return func(*args, **kwargs)
 return wrapper
if __name__ == "__main__":
 a1 = np.asarray([0, 1, 2])
 print(f'a1={a1}')
 a2 = np.array([0, 1, 2])
 print(f'a2={a2}')
 np.array = log(np.array)
 a3 = np.asarray([0, 1, 2])
 print(f'a3={a3}')
 a4 = np.array([0, 1, 2])
 print(f'a4={a4}')

The output is:

a1=[0 1 2]
a2=[0 1 2]
a3=[0 1 2]
logging
a4=[0 1 2]

I would like the result to be:

a1=[0 1 2]
a2=[0 1 2]
logging
a3=[0 1 2]
logging
a4=[0 1 2]

since asarray calls array in the source code.

My questions are: 1. Why monkey patch fails? 2. How to fix it?

asked Apr 17, 2019 at 6:52
2
  • 1
    ...what are you decorating with your log decorator? Commented Apr 17, 2019 at 6:54
  • @hiroprotagonist np.array methods, my terminology is wrong, I guess. Commented Apr 17, 2019 at 6:56

1 Answer 1

2

By np.array = log(np.array) you are changing which function the "public" name np.array refers to.

But np.asarray is defined in the numpy.core.numeric module, which has its own "private" name to refer to that function. It is not affected by patching the public name.

You would have to patch the private name:

np.core.numeric.array = log(np.array)
answered Apr 18, 2019 at 9:44
Sign up to request clarification or add additional context in comments.

2 Comments

In this way, I have to patch both the public name (np.array = log(np.array)) and private name (np.core.numeric.array = log(np.array)), and every other private name that calls np.arrray. Is it possible for me to patch only once?
I don't think that's possible. However, by patching np.core.numeric.array, you already cover a lot of functions.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.