Simply put, Monkey Patching is the dynamic replacement of attributes at runtime. Monkey Patching can only be done in dynamic languages, of which Python is a good example.

In Python, patching module (or class) variables or functions is simple, because Python doesn’t create protected or private entities– and in most cases, it is possible to get reference to them.

Monkey Patching is typically done when a developer needs to modify or extend the behavior of a third-party product. In other words, the developer required the current instance to be patched, so they can build something on top of the existing method and not replace it entirely.

Problem Statement:

I want the functionality of a certain library to be upgraded. I cannot modify the source of a library when using it. Doing so makes upgrades of the library a potential nightmare, making general maintenance impossible. As I cannot wait for the library creators to fix their bug, I change the behavior of the existing function at runtime by Monkey Patching the required one. Let’s understand this with a simple example:

The above example shows a class third party which has display method, which is successfully modified at runtime using Monkey Patching.

Leave a Reply

Your email address will not be published. Required fields are marked *