What is monkey patching in Python?

Imagine you're working on a project using a third-party library. You encounter a bug, but waiting for an official update isn't an option. This is where monkey patching comes in—it lets you fix or modify the library's code directly, making it behave differently without altering the original codebase.

Monkey patching in Python refers to the dynamic modification of a class or module at runtime. This technique enables you to change or extend the behavior of existing code, making it a useful tool in scenarios where third-party libraries need adjustments. It is an advanced topic in Python and to understand it one must have clarity about functions and how functions are treated in Python.

Monkey patch 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.

Steps to perform monkey patching

Have a look at the steps required for monkey patching:

  • Define the original class or method: Create a class or method that you want to modify later.

  • Create the patch (Replacement method): Define the new function that you want to replace the original method with.

  • Apply the monkey patch: Assign the new function to the existing method of the class or object.

  • Test the patch: Create an object of the class and call the method to confirm that it has been replaced.

Let's look at the code snippet below.

# Original Class
class Power:
def square(self, num):
return f"Square of {num} is: {num**2}"
# Creating an object of Power
obj = Power()
print(obj.square(3)) # Expected output: Square of 3 is: 9

Code explanation

  • Line 1: We create the class Power.

  • Lines 3 and 4: We create a function that returns the square of the input number.

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

Monkey patch implementation

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 the original file
import Old
# Define the replacement function
def cube(self, num):
return f"Cube of {num} is: {num**3}"
# Monkey Patching
Old.Power.square = cube # Assigning the new 'cube' method to replace 'square'
# Testing the patch
obj = Old.Power()
print(obj.square(3)) # Expected output: Cube of 3 is: 27

Code explanation

  • Line 2: We imported the previously created file, i.e., Old.py.

  • Lines 5 and 6: We create a function that returns the cube of the input number.

  • Line 9: We perform the monkey patching.

  • Lines 12 and 13: 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 9 (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.

Want to take it a step further? Try modifying the code yourself!

Change the cube function to calculate the fourth power of the number instead. Observe how this affects the output.

Practice problem

Here’s a mini-challenge:

    • Define a Person class with a method called greet that returns a simple greeting message.

    • Define a new function called custom_greet outside the class, which accepts self as a parameter and returns a customized greeting message.

    • Apply monkey patching to replace the original greet method in the Person class with custom_greet.

    • Create an instance of Person and call the greet method to see the modified behavior.

After you try it yourself first, refer to the given solution by pressing the "Run" button if you're stuck.

# Write your code here

Key takeaways

  • Monkey patching allows the dynamic modification of classes or modules at runtime, enabling you to change behaviors without altering the original code.

  • It's useful for fixing or enhancing third-party libraries, especially when source code access is restricted.

  • Steps for monkey patching: Define the original class, create a new function (patch), apply the patch, and test.

  • Monkey patching should be used carefully, as it can cause confusion in teams and lead to discrepancies between the original code and its behavior.

  • While powerful, excessive use of monkey patching can lead to maintenance difficulties, especially in collaborative projects.

  • Best practice is to use monkey patching only when necessary and ensure it's well documented for clarity among team members.

Become a Python developer with our comprehensive learning path!

Ready to kickstart your career as a Python Developer? Our Become a Python Developer path is designed to take you from your first line of code to landing your first job.

This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


When should monkey patching be used?

Monkey patching should be used when you need to modify third-party or built-in libraries that you can’t modify directly. It’s best used for quick fixes, bug patches, or adding new functionality in a controlled environment.


What are the drawbacks of using monkey patching in Python?

Unexpected behavior, potential maintenance issues, difficulty in debugging, and version compatibility problems when the original code changes.


Can monkey patching be done for built-in Python libraries?

Yes, you can apply monkey patching to built-in Python libraries, but it’s risky because future Python updates may render the patch incompatible.


Is monkey patching the same as dependency injection?

No, monkey patching is not the same as dependency injection. Dependency injection is a design pattern for managing dependencies, whereas monkey patching dynamically modifies existing code.


What is a common mistake when using monkey patching?

One common mistake is overusing monkey patching. Relying on it too frequently can lead to code that is difficult to understand and maintain, as it obscures the original functionality of the code.


Free Resources