SoFunction
Updated on 2024-11-17

Examples of Python Monkey Patch usage

The dynamic replacement of properties at runtime is called a Monkey Patch.

Why are they called monkey patches?

Runtime replacement of properties has nothing to do with monkeys either, and there are two accounts of the origin of the monkey patch found online:

1. This word originally for Guerrilla Patch, miscellaneous army, guerrilla, indicating that this part is not original, in English guerilla pronunciation and gorilla (ape) similar, and then later wrote monkey (monkey).

2. There is another explanation is that because of this way to mess up the original code (messing with it), in English called monkeying about (naughty), so called Monkey Patch.

Monkey patches are called "monkey patches" for some reason, as long as they correspond to "functions that are replaced at runtime by the module".

Monkey Patch Usage

1. Runtime dynamic replacement of modules

There are two hotter examples on * that

consider a class that has a method get_data. This method does an
external lookup (on a database or web API, for example), and various
other methods in the class call it. However, in a unit test, you don't
want to depend on the external data source - so you dynamically
replace the get_data method with a stub that returns some fixed data.

Suppose a class has a method get_data. this method does some external querying (e.g., querying a database or Web API, etc.), and many other methods inside the class call it. However, in a unit test, you don't want to rely on an external data source. So you replace this get_data method with a dummy method state, which returns only some test data.

Another example cited is the Monkey Patch explanation on the Zope wiki:

from  import SomeClass
def speak(self):
  return "ook ook eee eee eee!"
 = speak

There is also a more practical example, a lot of code using import json, and later found that ujson performance is higher, if you feel that the import json of each file to import ujson as json cost more, or want to test whether replacing json with ujson meets the expectations, just need to be added in the entrance:

import json
import ujson
def monkey_patch_json():
  json.__name__ = 'ujson'
   = 
   = 
monkey_patch_json()

2. Methods for dynamically adding modules at runtime

There are many scenarios where we refer to a module in the team's common library and want to enrich the functionality of the module. In addition to inheritance, we can also consider using Monkey Patch.

Personally, I feel that Monkey Patch brings convenience but also the risk of messing up the elegance of the source code.

This is the whole content of this article.