知行编程网知行编程网  2023-01-03 05:00 知行编程网 隐藏边栏  1 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python中猴子补丁是什么?的相关知识,希望可以帮到处于编程学习途中的小伙伴

什么是 Python 中的猴子补丁?


属性在运行时的动态替换,叫做猴子补丁(Monkey Patch)。


为什么叫猴子补丁

属性的运行时替换与猴子无关。网上查到猴子补丁的来历有两种说法:

1.词原为Guerrilla Patch,杂军,游击队,说明这部分不是原创。在英语中,guerilla的读音与gorllia(猩猩)相似,后来才写成monkey(猴子)。

2、另一种解释是因为这种方法把原来的代码弄乱了(messing with it),英文叫monkeying about(淘气),所以叫Monkey Patch。

monkey patch的名字有点莫名其妙,只要对应“运行时被模块替换的功能”即可。


猴子补丁的用法


1、运行时动态替换模块的方法

stackoverflow上有两个比较热的例子,

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.

假设一个类有一个方法 get_data。这个方法做一些外部查询(比如查询数据库或者Web API等),类中的很多其他方法都会调用它。但是,在单元测试中,你不想依赖外部数据源。因此,你将这个 get_data 方法替换为一个只返回一些测试数据的愚蠢方法。

另一个例子引用了,Zope wiki上对Monkey Patch解释:

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

还有一个更实际的例子。很多代码使用import json,后来发现ujson性能更高。如果你觉得改变每个文件的import json为import ujson as json成本高,或者你想测试一下,把json换成ujson是否符合预期,补充一下:

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


2、运行时动态增加模块的方法

这样的场景还有很多。比如我们引用了团队通用库中的某个模块,想要丰富该模块的功能,除了继承之外,我们也可以考虑使用Monkey Patch。

个人觉得Monkey Patch在带来便利的同时,也存在着把源码的优雅搞得一团糟的风险。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享