What is monkey patching? How to use it in Python?

Technology CommunityCategory: PythonWhat is monkey patching? How to use it in Python?
VietMX Staff asked 3 years ago

MonkeyPatch is a piece of Python code which extends or modifies other code at runtime (typically at startup).

Consider:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
    return "ook ook eee eee eee!"

SomeClass.speak = speak

It is often used to replace a method on the module or class level with a custom implementation.

The most common usecase is adding a workaround for a bug in a module or class when you can’t replace the original code. In this case you replace the “wrong” code through monkey patching with an implementation inside your own module/package.