Trusted answers to developer questions

What is monkey patching in Python?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

Solution approach

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 interpreted languageThe source code is converted into bytecode which is then executed by the Python virtual machine, allows us to do run-time modifications. We can reopen the class and modify its behavior using monkey patching and the same will be illustrated via code.

Code

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))

Explanation

  • 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 as Old.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.

main.py
Old.py
import Old
def cube(self, num):
return f"Cube of {num} is: {num**3}"
# Monkey Patching
Old.Power.square = cube
obj = Old.Power()
print(obj.square(3))

Explanation

  • 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

python
Did you find this helpful?