详解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自定义解析简单xml格式文件的方法
May 11 Python
python实现闹钟定时播放音乐功能
Jan 25 Python
Python中的Django基本命令实例详解
Jul 15 Python
对python数据切割归并算法的实例讲解
Dec 12 Python
Python 3.6 -win64环境安装PIL模块的教程
Jun 20 Python
详解python列表(list)的使用技巧及高级操作
Aug 15 Python
浅谈Python_Openpyxl使用(最全总结)
Sep 05 Python
在jupyter notebook 添加 conda 环境的操作详解
Apr 10 Python
python 进程池pool使用详解
Oct 15 Python
python 实现图片批量压缩的示例
Dec 18 Python
Python趣味爬虫之用Python实现智慧校园一键评教
May 28 Python
python开发制作好看的时钟效果
May 02 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函数之子字符串替换 str_replace
2011/03/23 PHP
php防止恶意刷新与刷票的方法
2014/11/21 PHP
php替换字符串中间字符为省略号的方法
2015/05/04 PHP
PHP查询分页的实现代码
2017/06/09 PHP
LaravelS通过Swoole加速Laravel/Lumen详解
2018/03/02 PHP
弹出层之1:JQuery.Boxy (一) 使用介绍
2011/10/06 Javascript
jQuery.query.js 取参数的两点问题分析
2012/08/06 Javascript
JavaScript执行顺序详细介绍
2013/12/04 Javascript
动态载入js提高网页打开速度的方法
2014/07/04 Javascript
JS实现可点击展开与关闭的左侧广告代码
2015/09/02 Javascript
jQuery与Ajax以及序列化
2016/02/01 Javascript
JavaScript实现前端分页控件
2017/04/19 Javascript
NodeJS实现图片上传代码(Express)
2017/06/30 NodeJs
vue+mockjs模拟数据实现前后端分离开发的实例代码
2017/08/08 Javascript
vue将对象新增的属性添加到检测序列的方法
2018/02/24 Javascript
Vue开发之封装分页组件与使用示例
2019/04/25 Javascript
JavaScript 判断浏览器是否是IE
2021/02/19 Javascript
Python中方法链的使用方法
2016/02/23 Python
Python3爬虫学习之爬虫利器Beautiful Soup用法分析
2018/12/12 Python
python实时获取外部程序输出结果的方法
2019/01/12 Python
Python利用字典破解WIFI密码的方法
2019/02/27 Python
在Pycharm中调试Django项目程序的操作方法
2019/07/17 Python
django中使用事务及接入支付宝支付功能
2019/09/15 Python
使用python实现希尔、计数、基数基础排序的代码
2019/12/25 Python
keras 读取多标签图像数据方式
2020/06/12 Python
马来西亚与新加坡长途巴士售票网站:BusOnlineTicket.com
2018/11/05 全球购物
创先争优制度
2014/01/21 职场文书
2014年元旦联欢会活动策划方案
2014/02/16 职场文书
中国好声音广告词
2014/03/18 职场文书
2014年应急管理工作总结
2014/11/26 职场文书
2015年电信员工工作总结
2015/05/26 职场文书
2016学校元旦晚会经典开场白台词
2015/12/03 职场文书
职场干货:简历中的自我评价应该这样写!
2019/05/06 职场文书
如何用RabbitMQ和Swoole实现一个异步任务系统
2021/05/29 PHP
Java中常用解析工具jackson及fastjson的使用
2021/06/28 Java/Android