Link Search Menu Expand Document

Monkey patching

Monkey patching is a technique in Python that allows us to modify the behavior of a class at runtime. In other words, it allows us to change one method for another. Imagine that we have a greet method.

class Person:
    def greet(self):
        print("Hello!")

Thanks to monkey patching, we can change the greet method to new_greet at runtime.

def new_greet(self):
    print("Hello world!")

Person.greet = new_greet
p = Person()
p.greet()
# Hello world!

This is quite interesting for testing. Also, if you want to modify the functionality of third-party code quickly.

However, use it with care, as it can be confusing. For example, it is not recommended to modify Python packages, since everyone expects a certain behavior. You will confuse the readers of your code.