/  Technology   /  Python   /  What is monkey patching in python?
Monke Patching(i2tutorials.com)

What is monkey patching in python?

Python is a dynamic programming language and therefore the classes in python are mutable so that you can reopen them, modify, or even replace them. In simple words, monkey patching is making changes to a module or class while the program is running. It refers to reopening the existing classes or methods in class at runtime and changing their behavior according to the requirement. This code can be used whenever you need it. A Monkey Patch is a piece of Python code which extends or modifies other code at runtime.

Example:

# monk.py

 class A:

                         def func(self):

                         print "func() is being called"

We can now use the above module in the code below and change the behavior of the func() at run-time by assigning a different value to it.

import monk

def monkey_f(self):

 print "monkey_f() is being called"

   # replacing address of "func" with "monkey_f"

monk.A.func = monkey_f

obj = monk.A()

  # calling function "func" whose address got replaced

# with function "monkey_f()"

obj.func()

 Output : monkey_f() is being called

 

Leave a comment