详解Python编程中对Monkey Patch猴子补丁开发方式的运用


Posted in Python onMay 27, 2016

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。

Python 相关文章推荐
Linux下使用python调用top命令获得CPU利用率
Mar 10 Python
Python中shutil模块的学习笔记教程
Apr 04 Python
python中numpy包使用教程之数组和相关操作详解
Jul 30 Python
Anaconda多环境多版本python配置操作方法
Sep 12 Python
python pandas修改列属性的方法详解
Jun 09 Python
python创建与遍历List二维列表的方法
Aug 16 Python
Python pandas.DataFrame 找出有空值的行
Sep 09 Python
Python搭建代理IP池实现获取IP的方法
Oct 27 Python
Django中使用MySQL5.5的教程
Dec 18 Python
pytorch实现建立自己的数据集(以mnist为例)
Jan 18 Python
Python3 字典dictionary入门基础附实例
Feb 10 Python
Django模型层实现多表关系创建和多表操作
Jul 21 Python
Python程序中的观察者模式结构编写示例
May 27 #Python
Windows下python2.7.8安装图文教程
May 26 #Python
Java Web开发过程中登陆模块的验证码的实现方式总结
May 25 #Python
剖析Python的Twisted框架的核心特性
May 25 #Python
实例解析Python的Twisted框架中Deferred对象的用法
May 25 #Python
详解Python的Twisted框架中reactor事件管理器的用法
May 25 #Python
使用Python的Twisted框架编写非阻塞程序的代码示例
May 25 #Python
You might like
PHP解析RSS的方法
2015/03/05 PHP
laravel 之 Eloquent 模型修改器和序列化示例
2019/10/17 PHP
基于jQuery制作迷你背词汇工具
2010/07/27 Javascript
原生javascript兼容性测试实例
2013/07/01 Javascript
基于JavaScript 下namespace 功能的简单分析
2013/07/05 Javascript
Javascript call和apply区别及使用方法
2013/11/14 Javascript
关于jQuery中的each方法(jQuery到底干了什么)
2014/03/05 Javascript
Iframe实现跨浏览器自适应高度解决方法
2014/09/02 Javascript
javascript比较两个日期的先后示例代码
2014/12/31 Javascript
JS实现可直接显示网页代码运行效果的HTML代码预览功能实例
2015/08/06 Javascript
js一维数组、多维数组和对象的混合使用方法
2016/04/03 Javascript
关于JavaScript数组你所不知道的3件事
2016/08/24 Javascript
Vue.js表单控件实践
2016/10/27 Javascript
Vue.js学习之过滤器详解
2017/01/22 Javascript
JSONP基础知识详解
2017/03/19 Javascript
js实现敏感词过滤算法及实现逻辑
2018/07/24 Javascript
js实现移动端图片滑块验证功能
2020/09/29 Javascript
Python里隐藏的“禅”
2014/06/16 Python
python实现随机梯度下降(SGD)
2020/03/24 Python
彻底搞懂Python字符编码
2018/01/23 Python
Python绘图Matplotlib之坐标轴及刻度总结
2019/06/28 Python
python pandas生成时间列表
2019/06/29 Python
Python如何基于rsa模块实现非对称加密与解密
2020/01/03 Python
Django实现任意文件上传(最简单的方法)
2020/06/03 Python
keras 获取某层的输入/输出 tensor 尺寸操作
2020/06/10 Python
HTML5实现分享到微信好友朋友圈QQ好友QQ空间微博二维码功能
2018/01/03 HTML / CSS
HTML5中外部浏览器唤起微信分享
2020/01/02 HTML / CSS
详解如何将 Canvas 绘制过程转为视频
2021/01/25 HTML / CSS
美国乡村商店:Plow & Hearth
2016/09/12 全球购物
模具设计与制造专业应届生求职信
2013/10/18 职场文书
电子信息科学专业自荐信
2014/01/30 职场文书
文艺晚会主持词
2014/03/24 职场文书
2014小学数学教研组工作总结
2014/12/06 职场文书
英文邀请函
2015/02/02 职场文书
付款证明模板
2015/06/19 职场文书
廉洁自律承诺书2016
2016/03/25 职场文书