详解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 相关文章推荐
python3中bytes和string之间的互相转换
Feb 09 Python
python字符串过滤性能比较5种方法
Jun 22 Python
Python实现1-9数组形成的结果为100的所有运算式的示例
Nov 03 Python
python切片及sys.argv[]用法详解
May 25 Python
Python3+django2.0+apache2+ubuntu14部署网站上线的方法
Jul 07 Python
Python SMTP发送邮件遇到的一些问题及解决办法
Oct 24 Python
python中dir()与__dict__属性的区别浅析
Dec 10 Python
零基础使用Python读写处理Excel表格的方法
May 02 Python
flask/django 动态查询表结构相同表名不同数据的Model实现方法
Aug 29 Python
python pygame实现球球大作战
Nov 25 Python
python 多线程死锁问题的解决方案
Aug 25 Python
python实现在列表中查找某个元素的下标示例
Nov 16 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
《逃离塔科夫》——“萌新劝退,老手自嗨”的硬核FPS游戏
2020/04/03 其他游戏
php预定义常量
2006/12/25 PHP
几个php应用技巧
2008/03/27 PHP
PHP 批量删除 sql语句
2009/06/05 PHP
php下批量挂马和批量清马代码
2011/02/27 PHP
调试一段PHP程序时遇到的三个问题
2012/01/17 PHP
PHP删除数组中空值的方法介绍
2014/04/14 PHP
php中HTTP_REFERER函数用法实例
2014/11/21 PHP
php关键字仅替换一次的实现函数
2015/10/29 PHP
PHP生成图片缩略图类示例
2017/01/12 PHP
PHP去除字符串最后一个字符的三种方法实例
2017/03/01 PHP
JavaScript Event学习第十章 一些可替换的事件对
2010/02/10 Javascript
jquery中animate动画积累的解决方法
2013/10/05 Javascript
JavaScript动态创建div属性和样式示例代码
2013/10/09 Javascript
jQuery is()函数用法3例
2014/05/06 Javascript
JS+CSS实现另类带提示效果的竖向导航菜单
2015/10/15 Javascript
thinkjs之页面跳转同步异步操作
2017/02/05 Javascript
使用store来优化React组件的方法
2017/10/23 Javascript
封装 axios+promise通用请求函数操作
2020/08/11 Javascript
如何封装Vue Element的table表格组件
2021/02/06 Vue.js
[00:43]DOTA2小紫本全民票选福利PA至宝全方位展示
2014/11/25 DOTA
对python3 urllib包与http包的使用详解
2018/05/10 Python
Python 学习教程之networkx
2019/04/15 Python
解决pycharm remote deployment 配置的问题
2019/06/27 Python
用python实现前向分词最大匹配算法的示例代码
2020/08/06 Python
python实现逻辑回归的示例
2020/10/09 Python
Django配置Bootstrap, js实现过程详解
2020/10/13 Python
苹果美国官方商城:Apple美国
2016/08/24 全球购物
家得宝加拿大家装网上商店:The Home Depot加拿大
2016/08/27 全球购物
市优秀教师事迹材料
2014/02/05 职场文书
导游词之绍兴柯岩古镇
2020/01/09 职场文书
Nginx反爬虫策略,防止UA抓取网站
2021/03/31 Servers
Html5通过数据流方式播放视频的实现
2021/04/27 HTML / CSS
带你了解CSS基础知识,样式
2021/07/21 HTML / CSS
记一次Mysql不走日期字段索引的原因小结
2021/10/24 MySQL
MySQL中order by的使用详情
2021/11/17 MySQL