Python Monkey patch猴子补丁
monkey patch (猴子补丁)
用来在运行时动态修改已有的代码,而不需要修改原始代码。
简单的monkey patch 实现:
[python]
#coding=utf-8
def originalFunc():
print 'this is original function!'
def modifiedFunc():
modifiedFunc=1
print 'this is modified function!'
def main():
originalFunc()
if __name__=='__main__':
originalFunc=modifiedFunc
main()
python中所有的东西都是object,包括基本类型。查看一个object的所有属性的方法是:dir(obj)
函数在python中可以像使用变量一样对它进行赋值等操作。
查看属性的方法:
print locals()
print globals()
当我们import一个module时,python会做以下几件事情
•导入一个module
•将module对象加入到sys.modules,后续对该module的导入将直接从该dict中获得
•将module对象加入到globals dict中
当我们引用一个模块时,将会从globals中查找。这里如果要替换掉一个标准模块,我们得做以下两件事情
1.将我们自己的module加入到sys.modules中,替换掉原有的模块。如果被替换模块还没加载,那么我们得先对其进行加载,否则第一次加载时,还会加载标准模块。(这里有一个import hook可以用,不过这需要我们自己实现该hook,可能也可以使用该方法hook module import)
2.如果被替换模块引用了其他模块,那么我们也需要进行替换,但是这里我们可以修改globals dict,将我们的module加入到globals以hook这些被引用的模块。
一篇文章:
What is Monkey Patch
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。
转自:http://blog.csdn.net/seizef/article/details/5732657
Python Monkey patch猴子补丁的更多相关文章
- python中的猴子补丁Monkey Patch
python中的猴子补丁Monkey Patch 什么是猴子补丁 the term monkey patch only refers to dynamic modifications of a cla ...
- python设计模式之猴子补丁模式
1.所有书中都没有把猴子补丁作为一种设计模式来看待.因为设计模式的模式的命名是根据java中提炼出来的,语言方式决定了java绝对不会有也不需要有这种操作,不存在的.那自然设计模式不会包括猴子补丁模式 ...
- Python中的猴子补丁
monkey patch指的是在运行时动态替换,一般是在startup的时候.用过gevent就会知道,会在最开头的地方gevent.monkey.patch_all();把标准库中的thread/s ...
- 协程gevent模块和猴子补丁
# pip 装模块 greenlet和gevent # 协程 # 与进程.线程一样也是实现并发的手段 # 创建一个线程.关闭一个线程都需要创建寄存器.栈等.需要消耗时间 # 协程本质上是一个线程 # ...
- python的猴子补丁monkey patch
monkey patch指的是在运行时动态替换,一般是在startup的时候. 用过gevent就会知道,会在最开头的地方gevent.monkey.patch_all();把标准库中的thread/ ...
- python monkey 猴子补丁技术编程,修改python json dumps方法。
1.猴子补丁就是不改变原有模块的内容的前提下,给原有模块新增方法或者修改原有模块. 一个模块的函数,如果希望改变函数的功能,不改变函数名,通常是库模块,你不可能去修改三方库的源码的,实施起来不方便,而 ...
- Python面试题之“猴子补丁”(monkey patching)指的是什么?这种做法好吗?
“猴子补丁”就是指,在函数或对象已经定义之后,再去改变它们的行为. 举个例子: import datetime datetime.datetime.now = lambda: datetime.dat ...
- 什么是猴子补丁(monkey patch)
monkey patch指的是在执行时动态替换,通常是在startup的时候. 用过gevent就会知道,会在最开头的地方gevent.monkey.patch_all();把标准库中的thread/ ...
- 猴子补丁(Monkey Patching)
猴子补丁是我在面试的时候接触的一到题,学python的时候,我根本就没有听说这个概念!那接下来我们来分析一下: 1.什么是猴子补丁? 2.猴子补丁的功能? 3.猴子补丁的应用场景? 一.什么是猴子补丁 ...
随机推荐
- mysql查询练习
mysql> #查询每个栏目最贵的商品 mysql> select goods_id,shop_price,cat_id from (select goods_id,shop_price, ...
- Java Mybatis 传参方式
一.单个参数: public List<XXBean> getXXBeanList(String xxCode); <select id="getXXXBeanList&q ...
- 20160427Struts2--入门1
参考资料来自传智播客:非原创,只是做个笔记: 一.Struts2简介: Struts2是在WebWork2基础发展而来的.和struts1一样, Struts2也属于MVC框架.不过有一点大家需要注意 ...
- 【C#】获取本地Cookie的问题
using System; using System.Net; using System.IO; using System.Text; // // TODO: 在此处添加代码以启动应用程序 // st ...
- iOS 查找字符串 相同 子字符串的位置 range
问题:解决替换同一个字符串的多个相同的字符eg. xxx这个超级大土豪白送xxx一个!赶快来抢把! 将第一个xxx换成名字 将第二个xxx换成物品 两种办法 第二种办法更灵活一点 //第一种办法 ...
- CSS背景属性
CSS背景属性 1.background-attachment 属性 scroll:默认值.背景图像会随着页面其余部分的滚动而移动. fixed:当页面的其余部分滚动时,背景图像不会移动. inher ...
- 使用Eclipse提供的Axis1.x生成WSDL文件以及Server和Client代码
使用Eclipse自带的Axis 1.x来创建一个web service应用的服务端和客户端 Axis 是SOAP WebService协议实现,SOAP实质上是一个基于HTTP POST的请求,以X ...
- Speak softly love
Speak softly love and hold me warm against your heart 柔声诉情,拥我在你暖暖的心上 I feel your words, the tender t ...
- 如何在WCF中集成unity
第一种是代码方式: 点击打开链接http://blogs.microsoft.co.il/gadib/2010/11/30/wcf-and-unity-20/ 还有一种方式可以扩展成配置文件,有时间再 ...
- 安装hadoop多节点 各种整理
ubuntu烧制usb启动盘链接: 点击打开链接https://help.ubuntu.com/community/Installation/FromUSBStick ubuntu磁盘分区: 点击打开 ...