What is Monkey Patching in Python

In Python, Monkey patching refers to the dynamic modifications of a class or module at runtime.
Monkey patching can only be done in dynamic languages. In Monkey patching, we are opening the existing classes or methods in class at runtime and altering the behavior. Since Python is a dynamic programming language, Classes are mutable, so you can reopen them and modify or even replace them.
Let’s see how Monkey patching is done in Python. Consider the below given class
class sample: def __init__(self, num): self.num = num def multiply(self, other): return (self.num * other) ob = sample(12) print(ob.multiply(4))
The output of the above code will be 48
.
Suppose now we want to add another function later in the code. Suppose this function is as follows.
def sum(self, other): return (self.num + other)
But how do we add this as a method in sample
? This can be done by placing that function into sample
with an assignment statement.
sample.sum = sum
Functions are objects just like any other object, and methods are functions that belong to the class.
The function sum
shall be available to all existing as well to the new instances of sample
. These additions are available on all instances of that class (or its subclasses) automatically. For example:
class sample: def __init__(self, num): self.num = num def multiply(self, other): return (self.num * other) def sum(self, other): return (self.num + other) ob = sample(12) sample.sum = sum print(ob.multiply(4)) print(ob.sum(4))
Output:
48 16