Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4470279
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Python/Ruby

2015-01-01 10:28:59

原文地址:http://blog.csdn.net/seizef/article/details/5732657

What is Monkey Patch

就是在运行时对已有的代码进行修改,达到hot patch的目的。Eventlet中大量使用了该技巧,以替换标准库中的组件,比如socket。首先来看一下最简单的monkey patch的实现。


  1. class Foo(object):  
  2.     def bar(self):  
  3.         print 'Foo.bar'  
  4.   
  5. def bar(self):  
  6.     print 'Modified bar'  
  7.   
  8. Foo().bar()  
  9.   
  10. Foo.bar = bar  
  11.   
  12. 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中查找。这里如果要替换掉一个标准模块,我们得做以下两件事情

  1. 将我们自己的module加入到sys.modules中,替换掉原有的模块。如果被替换模块还没加载,那么我们得先对其进行加载,否则第一次加载时,还会加载标准模块。(这里有一个import hook可以用,不过这需要我们自己实现该hook,可能也可以使用该方法hook module import)
  2. 如果被替换模块引用了其他模块,那么我们也需要进行替换,但是这里我们可以修改globals dict,将我们的module加入到globals以hook这些被引用的模块。

Eventlet Patcher Implementation

现在我们先来看一下eventlet中的Patcher的调用代码吧,这段代码对标准的ftplib做monkey patch,将eventlet的GreenSocket替换标准的socket。


  1. from eventlet import patcher  
  2.   
  3. # *NOTE: there might be some funny business with the "SOCKS" module  
  4. # if it even still exists  
  5. from eventlet.green import socket  
  6.   
  7. patcher.inject('ftplib', globals(), ('socket', socket))  
  8.   
  9. del patcher  

inject函数会将eventlet的socket模块注入标准的ftplib中,globals dict被传入以做适当的修改。

让我们接着来看一下inject的实现。

  1. __exclude = set(('__builtins__''__file__''__name__'))  
  2.   
  3. def inject(module_name, new_globals, *additional_modules):  
  4.     """Base method for "injecting" greened modules into an imported module.  It 
  5.     imports the module specified in *module_name*, arranging things so 
  6.     that the already-imported modules in *additional_modules* are used when 
  7.     *module_name* makes its imports. 
  8.  
  9.     *new_globals* is either None or a globals dictionary that gets populated 
  10.     with the contents of the *module_name* module.  This is useful when creating 
  11.     a "green" version of some other module. 
  12.  
  13.     *additional_modules* should be a collection of two-element tuples, of the 
  14.     form (, ).  If it's not specified, a default selection of 
  15.     name/module pairs is used, which should cover all use cases but may be 
  16.     slower because there are inevitably redundant or unnecessary imports. 
  17.     """  
  18.     if not additional_modules:  
  19.         # supply some defaults  
  20.         additional_modules = (  
  21.             _green_os_modules() +  
  22.             _green_select_modules() +  
  23.             _green_socket_modules() +  
  24.             _green_thread_modules() +  
  25.             _green_time_modules())  
  26.   
  27.     ## Put the specified modules in sys.modules for the duration of the import  
  28.     saved = {}  
  29.     for name, mod in additional_modules:  
  30.         saved[name] = sys.modules.get(name, None)  
  31.         sys.modules[name] = mod  
  32.   
  33.     ## Remove the old module from sys.modules and reimport it while  
  34.     ## the specified modules are in place  
  35.     old_module = sys.modules.pop(module_name, None)  
  36.     try:  
  37.         module = __import__(module_name, {}, {}, module_name.split('.')[:-1])  
  38.   
  39.         if new_globals is not None:  
  40.             ## Update the given globals dictionary with everything from this new module  
  41.             for name in dir(module):  
  42.                 if name not in __exclude:  
  43.                     new_globals[name] = getattr(module, name)  
  44.   
  45.         ## Keep a reference to the new module to prevent it from dying  
  46.         sys.modules['__patched_module_' + module_name] = module  
  47.     finally:  
  48.         ## Put the original module back  
  49.         if old_module is not None:  
  50.             sys.modules[module_name] = old_module  
  51.         elif module_name in sys.modules:  
  52.             del sys.modules[module_name]  
  53.   
  54.         ## Put all the saved modules back  
  55.         for name, mod in additional_modules:  
  56.             if saved[name] is not None:  
  57.                 sys.modules[name] = saved[name]  
  58.             else:  
  59.                 del sys.modules[name]  
  60.   
  61.     return module  

注释比较清楚的解释了代码的意图。代码还是比较容易理解的。这里有一个函数__import__,这个函数提供一个模块名(字符串),来加载一个模块。而我们import或者reload时提供的名字是对象。


  1. if new_globals is not None:  
  2.     ## Update the given globals dictionary with everything from this new module  
  3.     for name in dir(module):  
  4.         if name not in __exclude:  
  5.             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。

阅读(764) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~