Sunday, June 14, 2026
HomeLanguagesMonkey Patching in Python (Dynamic Behavior)

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.




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


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




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


Examples:

Output :monkey_f() is being called
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS