Monkey Patching in Python (Dynamic Behavior)

In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time.

filter_none

edit
close

play_arrow

link
brightness_4
code

# monk.py
class A:
     def func(self):
          print "func() is being called"

chevron_right


We use above module (monk) in below code and change behavior of func() at run-time by assigning different value.

filter_none

edit
close

play_arrow

link
brightness_4
code

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()

chevron_right


Examples:

Output :monkey_f() is being called


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.