详解Python编程中对Monkey Patch猴子补丁开发方式的运用
Monkeypatch就是在运行时对已有的代码进行修改,达到hotpatch的目的。Eventlet中大量使用了该技巧,以替换标准库中的组件,比如socket。首先来看一下最简单的monkeypatch的实现。
classFoo(object): defbar(self): print'Foo.bar' defbar(self): print'Modifiedbar' Foo().bar() Foo.bar=bar Foo().bar()
由于Python中的名字空间是开放,通过dict来实现,所以很容易就可以达到patch的目的。
Pythonnamespace
Python有几个namespace,分别是
- locals
- globals
- builtin
其中定义在函数内声明的变量属于locals,而模块内定义的函数属于globals。
PythonmoduleImport&NameLookup
当我们import一个module时,python会做以下几件事情
- 导入一个module
- 将module对象加入到sys.modules,后续对该module的导入将直接从该dict中获得
- 将module对象加入到globalsdict中
当我们引用一个模块时,将会从globals中查找。这里如果要替换掉一个标准模块,我们得做以下两件事情
将我们自己的module加入到sys.modules中,替换掉原有的模块。如果被替换模块还没加载,那么我们得先对其进行加载,否则第一次加载时,还会加载标准模块。(这里有一个importhook可以用,不过这需要我们自己实现该hook,可能也可以使用该方法hookmoduleimport)
如果被替换模块引用了其他模块,那么我们也需要进行替换,但是这里我们可以修改globalsdict,将我们的module加入到globals以hook这些被引用的模块。
EventletPatcherImplementation
现在我们先来看一下eventlet中的Patcher的调用代码吧,这段代码对标准的ftplib做monkeypatch,将eventlet的GreenSocket替换标准的socket。
fromeventletimportpatcher
#*NOTE:theremightbesomefunnybusinesswiththe"SOCKS"module
#ifitevenstillexists
fromeventlet.greenimportsocket
patcher.inject('ftplib',globals(),('socket',socket))
delpatcher
inject函数会将eventlet的socket模块注入标准的ftplib中,globalsdict被传入以做适当的修改。
让我们接着来看一下inject的实现。
__exclude=set(('__builtins__','__file__','__name__'))
definject(module_name,new_globals,*additional_modules):
"""Basemethodfor"injecting"greenedmodulesintoanimportedmodule.It
importsthemodulespecifiedin*module_name*,arrangingthingsso
thatthealready-importedmodulesin*additional_modules*areusedwhen
*module_name*makesitsimports.
*new_globals*iseitherNoneoraglobalsdictionarythatgetspopulated
withthecontentsofthe*module_name*module.Thisisusefulwhencreating
a"green"versionofsomeothermodule.
*additional_modules*shouldbeacollectionoftwo-elementtuples,ofthe
form(,).Ifit'snotspecified,adefaultselectionof
name/modulepairsisused,whichshouldcoverallusecasesbutmaybe
slowerbecausethereareinevitablyredundantorunnecessaryimports.
"""
ifnotadditional_modules:
#supplysomedefaults
additional_modules=(
_green_os_modules()+
_green_select_modules()+
_green_socket_modules()+
_green_thread_modules()+
_green_time_modules())
##Putthespecifiedmodulesinsys.modulesforthedurationoftheimport
saved={}
forname,modinadditional_modules:
saved[name]=sys.modules.get(name,None)
sys.modules[name]=mod
##Removetheoldmodulefromsys.modulesandreimportitwhile
##thespecifiedmodulesareinplace
old_module=sys.modules.pop(module_name,None)
try:
module=__import__(module_name,{},{},module_name.split('.')[:-1])
ifnew_globalsisnotNone:
##Updatethegivenglobalsdictionarywitheverythingfromthisnewmodule
fornameindir(module):
ifnamenotin__exclude:
new_globals[name]=getattr(module,name)
##Keepareferencetothenewmoduletopreventitfromdying
sys.modules['__patched_module_'+module_name]=module
finally:
##Puttheoriginalmoduleback
ifold_moduleisnotNone:
sys.modules[module_name]=old_module
elifmodule_nameinsys.modules:
delsys.modules[module_name]
##Putallthesavedmodulesback
forname,modinadditional_modules:
ifsaved[name]isnotNone:
sys.modules[name]=saved[name]
else:
delsys.modules[name]
returnmodule
注释比较清楚的解释了代码的意图。代码还是比较容易理解的。这里有一个函数__import__,这个函数提供一个模块名(字符串),来加载一个模块。而我们import或者reload时提供的名字是对象。
ifnew_globalsisnotNone: ##Updatethegivenglobalsdictionarywitheverythingfromthisnewmodule fornameindir(module): ifnamenotin__exclude: new_globals[name]=getattr(module,name)
这段代码的作用是将标准的ftplib中的对象加入到eventlet的ftplib模块中。因为我们在eventlet.ftplib中调用了inject,传入了globals,而inject中我们手动__import__了这个module,只得到了一个模块对象,所以模块中的对象不会被加入到globals中,需要手动添加。
这里为什么不用fromftplibimport*的缘故,应该是因为这样无法做到完全替换ftplib的目的。因为from…import*会根据__init__.py中的__all__列表来导入publicsymbol,而这样对于下划线开头的privatesymbol将不会导入,无法做到完全patch。