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 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
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 Classclass Power:def square(self, num):return f"Square of {num} is: {num**2}"# Creating an object of Powerobj = 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
objectand print it.
Note: The output is as expected i.e.,
Square of 3 is: 9. Let this code be saved asOld.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.
# Import the original fileimport Old# Define the replacement functiondef cube(self, num):return f"Cube of {num} is: {num**3}"# Monkey PatchingOld.Power.square = cube # Assigning the new 'cube' method to replace 'square'# Testing the patchobj = 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
objectand 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
Personclass with a method calledgreetthat returns a simple greeting message.Define a new function called
custom_greetoutside the class, which acceptsselfas a parameter and returns a customized greeting message.Apply monkey patching to replace the original
greetmethod in thePersonclass withcustom_greet.Create an instance of
Personand call thegreetmethod 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