详解Python编程中对Monkey Patch猴子补丁开发方式的运用
作者:有心故我在 发布时间:2021-04-15 00:17:15
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。
猜你喜欢
- 在使用django的modelform的时候,修改表单,图片在form表单显示的是一个链接。显示缩略图如下第一步:from django.f
- 在上一篇文章中,我整理了pandas在数据合并和重塑中常用到的concat方法的使用说明。在这里,将接着介绍pandas中也常常用到的joi
- 随着python的发展越来越好,用python的伙伴也越来越多。本人刚开始接触python的时候用的第一个集成环境就是Anaconda,因为
- 1.物体识别本案例实现对特殊颜色物体的识别,并实现根据物体位置的改变进行控制跟随。import cv2 as cv# 定义结构元素kerne
- 问题一:python启动报错api-ms-win-crt-process-l1-1-0.dll 丢失解决:下载api-ms-win-crt-
- 最常见的XML数据类型有:Element, Attribute,Comment, Text. &nbs
- openpyxl 的用法实例1.1 Openpyxl 库的安装使用openpyxl 模块是一个读写 Excel 2010 文档的 Pytho
- 这种情况在挂载脚本后无法答题,任何关于答题脚本的脚本都无法使用。看这个字体,已经读不出原文了,一开始以为是加密尝试使用加密算法破解,然后用B
- 经常看到朋友圈或者空间里有朋友发布照片时,将朋友圈的照片切分为九宫格,参考了一些大神的博客资料,现整理如下;将图片分拆成九宫格的思路:读取图
- 1、设置数据库模式为简单模式:打开SQL企业管理器,在控制台根目录中依次点开Microsoft SQL Server-->SQL Se
- 在java的应用中,我们经常会对数据库进行必要的操作,下来我们就了解一下如何用java连接mysql数据库 以及java连接sql serv
- 如果你计划将数据库从SQL Server 2000 升级到 SQL Server 2005。你在升级之前一定会测试每样东西,并且证明应用程序
- 在用户注册中最常见的安全验证之一就是邮箱验证。根据行业的一般做法,进行邮箱验证是避免潜在的安全隐患一种非常重要的做法,现在就让我们来讨论一下
- 一、数据无量纲化处理 (热力图)1.数据无量纲化处理(仅介绍本文用到的方法):min-max归一化该方法是对原始数据进行线性变换,
- array_unique() 定义和用法 array_unique() 函数移除数组中的重复的值,并返回结果数组。 当几个数组元素的值相等时
- 本文实例演示了Python生成pdf文件的方法,是比较实用的功能,主要包含2个文件。具体实现方法如下:pdf.py文件如下:#!/usr/b
- (一)原理 小偷程序实际上是通过了XML中的XMLHTTP组件调用其它网站上的网页。比如新闻小偷程序,
- 一、什么要备份数据库 ?在现实IT世界里,我们使用的服务器硬件可能因为使用时间过长,而发生故障;Windows系列服务器有可能蓝屏或者感染病
- 老师罚学生抄写英文单词,结果学生给抄成这样……
- 1、说明(1)写函数时,可以为每个参数指定默认值。当调用函数为参数提供实际参数时,Python将使用指定的实际参数;否则,将使用参数的默认值