1.

What is monkey patch in Python?

Answer»

Monkey PATCHES are dynamic (or run-time) alterations of a class or module in Python. We can TRULY CHANGE the behavior of code at runtime in Python.

Example:

# m.pyclass A: def func(SELF): print ("func() is CALLED")

In the code below, we use the above module (m) to change the behavior of func() at runtime by assigning a new value.

import mdef monkey_func(self): print ("monkey_func() is called") # replacing the address of "func" with "monkey_func"m.A.func = monkey_funcob = m.A() # calling the function "func"ob.func()

Output:

monkey_func() is called

Explanation: 

We have assigned the monkey_func to the address of “func” of class A. Thus, when we call the “func” function of “ob”, the monkey function is called.



Discussion

No Comment Found