详解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 相关文章推荐
Python学习小技巧之列表项的推导式与过滤操作
May 20 Python
通过Python实现自动填写调查问卷
Sep 06 Python
Python读取文件内容的三种常用方式及效率比较
Oct 07 Python
python+selenium实现登录账户后自动点击的示例
Dec 22 Python
python使用代理ip访问网站的实例
May 07 Python
Python中list查询及所需时间计算操作示例
Jun 21 Python
解决Python pandas df 写入excel 出现的问题
Jul 04 Python
Python使用pickle模块实现序列化功能示例
Jul 13 Python
django框架之cookie/session的使用示例(小结)
Oct 15 Python
PyCharm 专业版安装图文教程
Feb 20 Python
用于ETL的Python数据转换工具详解
Jul 21 Python
用Python编写简单的gRPC服务的详细过程
Jul 04 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调用数据库的存贮过程!
2006/10/09 PHP
php+js实现图片的上传、裁剪、预览、提交示例
2013/08/27 PHP
php截取中文字符串不乱码的方法
2013/12/25 PHP
实现PHP框架系列文章(6)mysql数据库方法
2016/03/04 PHP
使用php从身份证号中获取一系列线索(星座、生肖、生日等)
2016/05/11 PHP
php in_array() 检查数组中是否存在某个值详解
2016/11/23 PHP
yii2项目实战之restful api授权验证详解
2017/05/20 PHP
学习ExtJS Column布局
2009/10/08 Javascript
基于jquery的滚动新闻列表
2010/06/19 Javascript
THREE.JS入门教程(1)THREE.JS使用前了解
2013/01/24 Javascript
javascript动态创建及删除元素的方法
2014/12/22 Javascript
jQuery中 prop() attr()使用详解
2015/05/19 Javascript
JS+CSS实现简易实用的滑动门菜单效果
2015/09/18 Javascript
jQuery实现为LI列表前3行设置样式的方法【2种方法】
2016/09/04 Javascript
jquery select2的使用心得(推荐)
2016/12/04 Javascript
关于Webpack dev server热加载失败的解决方法
2018/02/22 Javascript
vue cli webpack中使用sass的方法
2018/02/24 Javascript
vue 表单输入格式化中文输入法异常问题
2018/05/30 Javascript
vue中v-model的应用及使用详解
2018/06/27 Javascript
jQuery阻止事件冒泡实例分析
2018/07/03 jQuery
webpack-url-loader 解决项目中图片打包路径问题
2019/02/15 Javascript
JS中数组实现代码(倒序遍历数组,数组连接字符串)
2019/12/29 Javascript
ant-design-vue 时间选择器赋值默认时间的操作
2020/10/27 Javascript
Python的Django框架使用入门指引
2015/04/15 Python
Python3.2中的字符串函数学习总结
2015/04/23 Python
用python记录运行pid,并在需要时kill掉它们的实例
2017/01/16 Python
Python爬取qq music中的音乐url及批量下载
2017/03/23 Python
python虚拟环境virtualenv的安装与使用
2017/09/21 Python
使用 pytorch 创建神经网络拟合sin函数的实现
2020/02/24 Python
CSS3移动端vw+rem不依赖JS实现响应式布局的方法
2019/01/23 HTML / CSS
canvas实现烟花的示例代码
2020/01/16 HTML / CSS
都柏林通行卡/城市通票:The Dublin Pass
2020/02/16 全球购物
老龄工作先进事迹
2014/08/15 职场文书
Pytorch中的学习率衰减及其用法详解
2021/06/05 Python
Java基于Dijkstra算法实现校园导游程序
2022/03/17 Java/Android
Redis sentinel哨兵集群的实现步骤
2022/07/15 Redis