monkey patch (猴子补丁)
用来在运行时动态修改已有的代码,而不需要修改原始代码。
简单的monkey patch 实现:
[Python]
#coding=utf-8
def originalFunc():
print 'this is original function!'
def modifiedFunc():
modifiedFunc=1
print 'this is modified function!'
def main():
originalFunc()
if __name__=='__main__':
originalFunc=modifiedFunc
main()
python中所有的东西都是object,包括基本类型。查看一个object的所有属性的方法是:dir(obj)
函数在python中可以像使用变量一样对它进行赋值等操作。
查看属性的方法:
[html]
print locals()
print globals()
当我们import一个module时,python会做以下几件事情
•导入一个module
•将module对象加入到sys.modules,后续对该module的导入将直接从该dict中获得
•将module对象加入到globals dict中
当我们引用一个模块时,将会从globals中查找。这里如果要替换掉一个标准模块,我们得做以下两件事情
1.将我们自己的module加入到sys.modules中,替换掉原有的模块。如果被替换模块还没加载,那么我们得先对其进行加载,否则第一次加载时,还会加载标准模块。(这里有一个import hook可以用,不过这需要我们自己实现该hook,可能也可以使用该方法hook module import)
2.如果被替换模块引用了其他模块,那么我们也需要进行替换,但是这里我们可以修改globals dict,将我们的module加入到globals以hook这些被引用的模块。
========================================================================================================================
What is Monkey Patch
Monkey patch就是在运行时对已有的代码进行修改,达到hot patch的目的。Eventlet中大量使用了该技巧,以替换标准库中的组件,比如socket。首先来看一下最简单的monkey patch的实现。
- class Foo(object):
- def bar(self):
- print 'Foo.bar'
- def bar(self):
- print 'Modified bar'
- Foo().bar()
- Foo.bar = bar
- Foo().bar()
由于Python中的名字空间是开放,通过dict来实现,所以很容易就可以达到patch的目的。
Python namespace
Python有几个namespace,分别是
- locals
- globals
- builtin
其中定义在函数内声明的变量属于locals,而模块内定义的函数属于globals。
Python module Import & Name Lookup
当我们import一个module时,python会做以下几件事情
- 导入一个module
- 将module对象加入到sys.modules,后续对该module的导入将直接从该dict中获得
- 将module对象加入到globals dict中
当我们引用一个模块时,将会从globals中查找。这里如果要替换掉一个标准模块,我们得做以下两件事情
- 将我们自己的module加入到sys.modules中,替换掉原有的模块。如果被替换模块还没加载,那么我们得先对其进行加载,否则第一次加载时,还会加载标准模块。(这里有一个import hook可以用,不过这需要我们自己实现该hook,可能也可以使用该方法hook module import)
- 如果被替换模块引用了其他模块,那么我们也需要进行替换,但是这里我们可以修改globals dict,将我们的module加入到globals以hook这些被引用的模块。
Eventlet Patcher Implementation
现在我们先来看一下eventlet中的Patcher的调用代码吧,这段代码对标准的ftplib做monkey patch,将eventlet的GreenSocket替换标准的socket。
- from eventlet import patcher
- # *NOTE: there might be some funny business with the "SOCKS" module
- # if it even still exists
- from eventlet.green import socket
- patcher.inject('ftplib', globals(), ('socket', socket))
- del patcher
inject函数会将eventlet的socket模块注入标准的ftplib中,globals dict被传入以做适当的修改。
让我们接着来看一下inject的实现。
- __exclude = set(('__builtins__', '__file__', '__name__'))
- def inject(module_name, new_globals, *additional_modules):
- """Base method for "injecting" greened modules into an imported module. It
- imports the module specified in *module_name*, arranging things so
- that the already-imported modules in *additional_modules* are used when
- *module_name* makes its imports.
- *new_globals* is either None or a globals dictionary that gets populated
- with the contents of the *module_name* module. This is useful when creating
- a "green" version of some other module.
- *additional_modules* should be a collection of two-element tuples, of the
- form (, ). If it's not specified, a default selection of
- name/module pairs is used, which should cover all use cases but may be
- slower because there are inevitably redundant or unnecessary imports.
- """
- if not additional_modules:
- # supply some defaults
- additional_modules = (
- _green_os_modules() +
- _green_select_modules() +
- _green_socket_modules() +
- _green_thread_modules() +
- _green_time_modules())
- ## Put the specified modules in sys.modules for the duration of the import
- saved = {}
- for name, mod in additional_modules:
- saved[name] = sys.modules.get(name, None)
- sys.modules[name] = mod
- ## Remove the old module from sys.modules and reimport it while
- ## the specified modules are in place
- old_module = sys.modules.pop(module_name, None)
- try:
- module = __import__(module_name, {}, {}, module_name.split('.')[:-1])
- if new_globals is not None:
- ## Update the given globals dictionary with everything from this new module
- for name in dir(module):
- if name not in __exclude:
- new_globals[name] = getattr(module, name)
- ## Keep a reference to the new module to prevent it from dying
- sys.modules['__patched_module_' + module_name] = module
- finally:
- ## Put the original module back
- if old_module is not None:
- sys.modules[module_name] = old_module
- elif module_name in sys.modules:
- del sys.modules[module_name]
- ## Put all the saved modules back
- for name, mod in additional_modules:
- if saved[name] is not None:
- sys.modules[name] = saved[name]
- else:
- del sys.modules[name]
- return module
注释比较清楚的解释了代码的意图。代码还是比较容易理解的。这里有一个函数__import__,这个函数提供一个模块名(字符串),来加载一个模块。而我们import或者reload时提供的名字是对象。
- if new_globals is not None:
- ## Update the given globals dictionary with everything from this new module
- for name in dir(module):
- if name not in __exclude:
- new_globals[name] = getattr(module, name)
这段代码的作用是将标准的ftplib中的对象加入到eventlet的ftplib模块中。因为我们在eventlet.ftplib中调用了inject,传入了globals,而inject中我们手动__import__了这个module,只得到了一个模块对象,所以模块中的对象不会被加入到globals中,需要手动添加。
这里为什么不用from ftplib import *的缘故,应该是因为这样无法做到完全替换ftplib的目的。因为from … import *会根据__init__.py中的__all__列表来导入public symbol,而这样对于下划线开头的private symbol将不会导入,无法做到完全patch。
==============================================================================================================================
通过 Monkeypatching 更好地测试(Better Debugging through Monkeypatching)
模块 buildbot.test.util.monkeypatches
包含几个对 Twisted 的monkey-patches,以便更好地检测错误。这些补丁不应该影响正确行为,因此值得在每个测试文件中包含这个:
from buildbot.test.util.monkeypatches import monkeypatch monkeypatch()
”
这个合成词两个部分,就其组成的单个部分而言都是常见词:monkey(猴子)、patches(补丁);那么 monkey-patches 到底是什么意思呢?
就其词源(Etymology)来说,这个合成词应该是一种类似于中文的鲁鱼亥豕:
据 wikipedia,这个词似乎来自于guerrilla patch,其意思为,在运行时悄悄地引用改变的代码。结果 guerrilla(游击队) 变成了gorilla(大猩猩), gorilla(大猩猩) 又变成了monkey(猴子) ,其目的似乎是不想叫补丁那么过于引人注目。(错误的衍生路线就是:guerrilla(游击队)-->因拼法相似误为gorilla(大猩猩),gorilla(大猩猩)又-->换为同义词 monkey(猴子),结果,guerrilla patch 就成了monkeypatch(猴子补丁)了)。
这个词的定义还因所用的上下文而有所不同,在 Python 中,仅仅指在运行时根据补丁的意图以现有的方法对类进行动态修改,对于一缺陷或者某一不再符合你设计的特征在一外部类中作为一种变通方法。在运行时对一个 类进行修改的其他形式,依据其内容不同有不同的名称。例如,在 Zope 与 Plone 中安全补丁经常是用动态的类修改进行的,但是它们叫做 hot fixes(热修改)。
在 Ruby 中,意思是对一个类的任何动态修改,常用作在运行时动态修改任何类的同义语。
在中有些人采用duck punching 代替monkey patching,源自于Ruby Python 中动态类型(dynamic typing)的扩充用法。
===============================================================================
转自:http://www.2cto.com/kf/201211/171518.html
http://blog.csdn.NET/seizef/article/details/5732657
http://complinguistic.blog.sohu.com/166997784.html
http://www.v2ex.com/t/63898