Monkey Patching is a dynamic (or run-time) procedure in Python that allows the modification or extension of a module or class. This technique lets you modify or add functionalities to an object, often used for quick fixes or modification without changing the original source code.
The term 'Monkey Patching' comes from the phrase 'Monkey Wrench', which signifies throwing a wrench into the gears of a machine to disrupt its usual flow - or disrupt the normal behavior or functionality of an object. 'Patching' refers to adding new components or fixing existing ones.
Put together, Monkey Patching represents the changes we make to Python modules during the execution to alter their behavior for our requirement.
Consider you have a class with a method get_desc() that you're using as a third-party library in your project. Now, suppose you want to change the functionality of this function in your project, but you don't have access to change the source code of this library. In that case, Monkey Patching will come as a handy tool.
Here is an example:
# Third-Party library class
class Country:
def get_desc(self):
return "This is a country"
# Our monkey patching method
def new_get_desc(self):
return "This country is incredible"
# Applying Monkey Patching
Country.get_desc = new_get_desc
# Now, it will print - "This country is incredible"
c = Country()
print(c.get_desc())
As you can see, we have overridden the function get_desc() in the class Country during the runtime. The new method new_get_desc() changed the behavior of the original method without accessing the source code of the third-party library class.
While Monkey Patching can be a useful and powerful tool, it's essential to use it sparingly and wisely. Overuse or improper use can lead to code that's difficult to debug and maintain because it alters the behavior of objects from what's expected based on their original source code. It's always recommended to consider the effect of monkey patching on your whole application and other applications that may be using the modules or classes you're seeking to change.
As a rule of thumb, Monkey Patching should be considered a last resort. Its usage should be limited to situations where other alternatives, like class inheritance, are not feasible or effective. Always prioritize code clarity and maintainability to produce software that's easy to understand, debug, and modify.