详解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爬虫之使用urllib2组件抓取网页内容
Nov 04 Python
浅析Python中的序列化存储的方法
Apr 28 Python
使用Python对Excel进行读写操作
Mar 30 Python
基于Python3 逗号代码 和 字符图网格(详谈)
Jun 22 Python
基于Django的python验证码(实例讲解)
Oct 23 Python
python 实现登录网页的操作方法
May 11 Python
对Python捕获控制台输出流的方法详解
Jan 07 Python
pandas DataFrame 行列索引及值的获取的方法
Jul 02 Python
python获取引用对象的个数方式
Dec 20 Python
Python3实现mysql连接和数据框的形成(实例代码)
Jan 17 Python
python给图像加上mask,并提取mask区域实例
Jan 19 Python
举例讲解Python装饰器
Dec 24 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
phpQuery让php处理html代码像jQuery一样方便
2015/01/06 PHP
PHP实现的带超时功能get_headers函数
2015/02/10 PHP
CodeIgniter配置之autoload.php自动加载用法分析
2016/01/20 PHP
Gambit vs ForZe BO3 第一场 2.13
2021/03/10 DOTA
用window.location.href实现刷新另个框架页面
2007/03/07 Javascript
Javascript 继承实现例子
2009/08/12 Javascript
详谈JavaScript 匿名函数及闭包
2014/11/14 Javascript
JQuery boxy插件在IE中边角图片不显示问题的解决
2015/05/20 Javascript
详解微信小程序 wx.uploadFile 的编码坑
2017/01/23 Javascript
js前端日历控件(悬浮、拖拽、自由变形)
2017/03/02 Javascript
详谈js使用in和hasOwnProperty获取对象属性的区别
2017/04/25 Javascript
vuejs事件中心管理组件间的通信详解
2017/08/09 Javascript
Vue框架里使用Swiper的方法示例
2018/09/20 Javascript
element vue Array数组和Map对象的添加与删除操作
2018/11/14 Javascript
VUE.js实现动态设置输入框disabled属性
2019/10/28 Javascript
使用JS来动态操作css的几种方法
2019/12/18 Javascript
vue模块移动组件的实现示例
2020/05/20 Javascript
Jquery 获取相同NAME 或者id删除行操作
2020/08/24 jQuery
python字符串加密解密的三种方法分享(base64 win32com)
2014/01/19 Python
python返回昨天日期的方法
2015/05/13 Python
Windows下Python3.6安装第三方模块的方法
2018/11/22 Python
PyCharm配置mongo插件的方法
2018/11/30 Python
Python3实现的简单工资管理系统示例
2019/03/12 Python
PyTorch笔记之scatter()函数的使用
2020/02/12 Python
pycharm实现在虚拟环境中引入别人的项目
2020/03/09 Python
keras model.fit 解决validation_spilt=num 的问题
2020/06/19 Python
最新PyCharm从安装到PyCharm永久激活再到PyCharm官方中文汉化详细教程
2020/11/17 Python
美国隐形眼镜销售网站:ContactsDirect
2017/10/28 全球购物
学校联谊活动方案
2014/02/15 职场文书
三八妇女节演讲稿
2014/05/27 职场文书
离婚协议书包括哪些内容
2014/10/16 职场文书
吃空饷专项整治方案
2014/10/27 职场文书
2014年客房部工作总结
2014/11/22 职场文书
试用期解除劳动合同通知书
2015/04/16 职场文书
《鲁班学艺》读后感3篇
2019/11/27 职场文书
python缺失值的解决方法总结
2021/06/09 Python