DEV Community

Hasan Sajedi
Hasan Sajedi

Posted on

3

Monkey Patching in Python

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

Output :monkey_f() is being called

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay