Monkey patching refers to the dynamic (run-time) modification of a class or module. It is an advanced topic in Python and to understand it one must have clarity about functions and how functions are treated in Python.
While working on a real-time project, it might so happen that the third-party library is not working well. In order to change it from our project end, monkey patching becomes very useful.
With monkey patching, we tend to change a particular code at runtime so that it behaves differently. Python, being an
Let’s look at the code snippet below.
class Power:def square(self, num):return f"Square of {num} is: {num**2}"obj = Power()print(obj.square(3))
In line 1 we create the class Power
.
In lines 3 and 4 we create a function that returns the square of the input number.
In lines 6 and 7 we create the class object
and print it.
Note: The output is as expected i.e.,
Square of 3 is: 9
. Let this code be saved asOld.py
.
Now, we will create another piece of code that will be required to change the behavior of the given function at run-time i.e., replace the defined function square
with the newly defined function cube
at the run-time itself.
import Olddef cube(self, num):return f"Cube of {num} is: {num**3}"# Monkey PatchingOld.Power.square = cubeobj = Old.Power()print(obj.square(3))
In line 1 we imported the previously created file, i.e., Old.py
.
In lines 3 and 4 we create a function that returns the cube of the input number.
In line 7 we perform the monkey patching.
In lines 9 and 10 we create the previously defined class object
and print it.
Note: This time the output becomes:
Cube of 3 is: 27
. This is because the operation performed in line 7 (monkey patching) changes the default function to a newly created function at run-time.
Monkey patching becomes useful in real-world applications, as we can use it to extend or modify the functionality of an existing class, assuming we don’t have any access to the original class.
Again, it should be used carefully. This is because while working on a team, it can create confusion amongst developers, especially for members other than the monkey patch’s author. It creates discrepancies between the original source code and observed behavior, which is why it should be used with care.
RELATED TAGS
CONTRIBUTOR