在js中,所有的對(duì)象都是開(kāi)放的,有時(shí)候會(huì)擴(kuò)展原有對(duì)象的行為(比如對(duì)數(shù)組的ECMA5 shim),這也稱為Monkey patching
String::dasherize = -> @replace /_/g, "-"
::代表原型的引用,js代碼如下
String.prototype.dasherize = function() {
return this.replace(/_/g, "-");
};
What is Monkey Patch
Monkey patch就是在運(yùn)行時(shí)對(duì)已有的代碼進(jìn)行修改,達(dá)到hot patch的目的。Eventlet中大量使用了該技巧,以替換標(biāo)準(zhǔn)庫(kù)中的組件,比如socket。首先來(lái)看一下最簡(jiǎn)單的monkey patch的實(shí)現(xiàn)。
[python] view plain copy print?
class Foo(object):
def bar(self):
print 'Foo.bar'
def bar(self):
print 'Modified bar'
Foo().bar()
Foo.bar = bar
Foo().bar()
由于Python中的名字空間是開(kāi)放,通過(guò)dict來(lái)實(shí)現(xiàn),所以很容易就可以達(dá)到patch的目的。
Python namespace
Python有幾個(gè)namespace,分別是
locals
globals
builtin
其中定義在函數(shù)內(nèi)聲明的變量屬于locals,而模塊內(nèi)定義的函數(shù)屬于globals。
Python module Import & Name Lookup
當(dāng)我們import一個(gè)module時(shí),python會(huì)做以下幾件事情
導(dǎo)入一個(gè)module
將module對(duì)象加入到sys.modules,后續(xù)對(duì)該module的導(dǎo)入將直接從該dict中獲得
將module對(duì)象加入到globals dict中
當(dāng)我們引用一個(gè)模塊時(shí),將會(huì)從globals中查找。這里如果要替換掉一個(gè)標(biāo)準(zhǔn)模塊,我們得做以下兩件事情
將我們自己的module加入到sys.modules中,替換掉原有的模塊。如果被替換模塊還沒(méi)加載,那么我們得先對(duì)其進(jìn)行加載,否則第一次加載時(shí),還會(huì)加載標(biāo)準(zhǔn)模塊。(這里有一個(gè)import hook可以用,不過(guò)這需要我們自己實(shí)現(xiàn)該hook,可能也可以使用該方法hook module import)
如果被替換模塊引用了其他模塊,那么我們也需要進(jìn)行替換,但是這里我們可以修改globals dict,將我們的module加入到globals以hook這些被引用的模塊。
Eventlet Patcher Implementation
現(xiàn)在我們先來(lái)看一下eventlet中的Patcher的調(diào)用代碼吧,這段代碼對(duì)標(biāo)準(zhǔn)的ftplib做monkey patch,將eventlet的GreenSocket替換標(biāo)準(zhǔn)的socket。
[python] view plain copy print?
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函數(shù)會(huì)將eventlet的socket模塊注入標(biāo)準(zhǔn)的ftplib中,globals dict被傳入以做適當(dāng)?shù)男薷摹?br />讓我們接著來(lái)看一下inject的實(shí)現(xiàn)。
[python] view plain copy print?
__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
注釋比較清楚的解釋了代碼的意圖。代碼還是比較容易理解的。這里有一個(gè)函數(shù)__import__,這個(gè)函數(shù)提供一個(gè)模塊名(字符串),來(lái)加載一個(gè)模塊。而我們import或者reload時(shí)提供的名字是對(duì)象。
[python] view plain copy print?
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)
這段代碼的作用是將標(biāo)準(zhǔn)的ftplib中的對(duì)象加入到eventlet的ftplib模塊中。因?yàn)槲覀冊(cè)趀ventlet.ftplib中調(diào)用了inject,傳入了globals,而inject中我們手動(dòng)__import__了這個(gè)module,只得到了一個(gè)模塊對(duì)象,所以模塊中的對(duì)象不會(huì)被加入到globals中,需要手動(dòng)添加。
這里為什么不用from ftplib import *的緣故,應(yīng)該是因?yàn)檫@樣無(wú)法做到完全替換ftplib的目的。因?yàn)閒rom … import *會(huì)根據(jù)__init__.py中的__all__列表來(lái)導(dǎo)入public symbol,而這樣對(duì)于下劃線開(kāi)頭的private symbol將不會(huì)導(dǎo)入,無(wú)法做到完全patch。
更多建議: