Monkey patching allows modifying existing code at runtime. In this tutorial, we will learn monkey patching in Python with examples.
Monkey patching is a technique in programming where you modify or extend existing code at runtime. It allows you to add, modify, or replace functionality in a class or module without directly modifying its source code. It’s often used to fix bugs, add functionality, or customize third-party libraries without modifying their source code.
The term “monkey” in this context implies that these changes are being made in a playful, somewhat experimental, and potentially risky manner, similar to how a monkey might tamper with things.
Let’s understand it with some examples.
import math math.pi = 3.2 #Monkey patching pi value print(math.pi)
Here we are monkey patching the value of pi in the maths module. The value of pi is approximated to 3.2.
Let’s understand how monkey patching can be used to extend a Python class. Suppose we have a MathOperations class with “add” member function.
class MathOperations: def add(self, a, b): return a + b
Suppose we want to add the “subtract” method to the MathOperations class we can monkey-patch it.
MathOperations.subtract = subtract
Now we have added subtract method to MathOperations class and we can use the subtract method :
math = MathOperations() result = math.subtract(5, 3) print(result)
Let’s understand dynamic behavior with one more example. Suppose we have a Greeting class defined in greetings.py file.
# greetings.py class Greeting: def greet(self): print("Hello!")
We will create a new module it will change the behaviour of greet function at run time.
from greetings import Greeting def display(self): print("Hello NoloWiz") Greeting.greet = display #monkey patching greeting = Greeting() greeting.greet()
Here greet function is replaced with newly defined display function.
When to Use Monkey Patching
In the following situations we can use Monkey patching:
- Third-party Libraries: When you need to add or modify functionality in a third-party library that you can’t modify directly, monkey patching can be used.
- Bug Fixes: If you encounter a bug in a library or framework and can’t wait for an official fix, you can patch it temporarily using monkey patching.
- Legacy Code: When working with legacy code that can’t be easily refactored, monkey patching can help you make necessary changes without rewriting the entire codebase.
- Experimental Code: In some cases, you might use monkey patching to experiment with new features or concepts before committing to a more permanent solution.