![]() |
VOOZH | about |
In Python, Monkey Patching refers to dynamically modifying or extending behavior of a class or module at runtime. This allows developers to change how functions, methods or classes behave without altering original source code.
Monkey patching is a powerful feature, but it should be used carefully because it can lead to unexpected behavior if not managed properly.
For Example: Suppose we have a module monk.py with a simple class:
Normally, calling func() would output:
func() is being called
For changing behavior at runtime we can replace func() method dynamically by assigning a new function to it:
Output
monkey_f() is being called
Explanation:
Monkey patching is useful in several scenarios:
Monkey patching allows modifying the behavior of classes or their instances at runtime.
Example 1: This example shows how to patch a method for a single instance without affecting other instances of same class.
Hello from monkey patch! Hello from B!
Explanation:
Example 2: This example shows how to patch square() for one instance so it acts as a cube calculator, while other instances keep original method.
27 9
Explanation:
Note: Monkey patching can break other code and make maintenance difficult. Use it cautiously mainly for testing, quick fixes or prototyping.