Monkey Patching in Python with Example
Adding attributes dynamically to class or changing behavior of class at run time is known as Monkey Patching.
In other words, the term monkey patching refers to dynamic modification of a class or module. Here the term dyanmic modification refers to run-time modification. In python, we can change code at run time.
Monkey patching is very useful to add or change behavior of imported third party code which does not act as you desire.
Monkey Patching Example
Consider you are working with fraction numbers using Fraction
class imported using from fractions import Fraction
. This class has attributes like numerator
, denominator
to access numerator and denominator of fraction number. For example:
from fractions import Fraction
frac = Fraction(7,9)
print('Numerator: ', frac.numerator)
print('Denominator: ', frac.denominator)
Output of the above program is:
Numerator: 7 Denominator: 9
While working, at some point, it is required to calculate inverse of fraction i.e. if it is 7/9
you require result of 9/7
, but Fraction
has no method like inverse()
. So you want to add this inverse()
method at run time like this:
# Monkey patching Example
from fractions import Fraction
# Monkey patching line :)
Fraction.inverse = lambda self: self.denominator/self.numerator
frac1 = Fraction(5,10)
print(frac1.inverse())
frac2 = Fraction(10,5)
print(frac2.inverse())
Output of the above program is:
2.0 0.5
So, what did you do here? You just monkey patched the Fraction class here!
You added the behavior of Fraction
by adding inverse()
method on it at run time. That is monkey patching, you monkey :)