Monkey Patching in Python

Rafsan Jany
Aug 31, 2018 · 1 min read

Let’s get into the Python’s Monkey Patch. Monkey Patching is nothing but replacing a class method with another method outside the class at run time.In a word, it changes a class at run time. Let’s do it:

class MonkeyPatch:
def monkey_1(self):
return “I am monkey_1 from MonkeyPatch”

Let’s check it out in IDLE:

print MonkeyPatch().monkey_1()

The resulted output is: I am monkey_1 from MonkeyPatch

Let’s define the other method which is going to replace the class method:

def monkey_2(self):
return “I am monkey_2”

We have declared monkey_2 method. Now we can get the same return value from the class method. Let’s see:

MonkeyPatch.monkey_1 = monkey_2
print MonkeyPatch.monkey_1

The resulted output is: I am monkey_2

Python Monkey Patching
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade