What is Python monkey patch

Replace dynamic properties at runtime, called monkey patch (Monkey Patch).

Why is it called monkey patch

Replace property runtime and monkeys will not matter, the origin of the Internet on the monkey patches found in two different ways:

1. The term for the original Guerrilla Patch, miscellaneous troops, guerrillas, indicating that this part is not original, guerilla pronunciation and gorllia (orangutan) similar to the English language, and then later wrote monkey (monkey).

2. Another explanation is that because in this way the original code messed up (messing with it), in the English language called monkeying about (naughty), so called Monkey Patch.

Monkey patch is called puzzling, as long as "the replacement of the runtime module features" correspond on the line.

Monkey patch usage

1, an alternative method of dynamic run-time module

Stackoverflow on two comparative examples of heat,

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. The way to do some of the outer query (such as query a database or Web API, etc.), many other method of the class have called it. However, in one test unit, you do not want to rely on external data sources. So you replaced the state with dummy method get_data this method, dumb method returns only some test data.

Another example cited, the Zope wiki to Monkey Patch explanation:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):

    return "ook ook eee eee eee!"

SomeClass.speak = speak

  There is also a more practical example, a lot of code to use import json, later found ujson higher performance, if they feel the import json each file into import ujson as json high costs, or that want to test with ujson replace json whether in line with expectations, just at the entrance plus:

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

  

2, the dynamic run-time method for increasing module

This scenario will be more, for example, we refer to a common library module team, want rich module functions, in addition to inheritance may also consider using Monkey Patch.

Monkey Patch personal feeling with the convenience, but also the risk of messing up the source code elegance.

Guess you like

Origin www.cnblogs.com/daniumiqi/p/12154808.html