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中可以像使用變量一樣對它進行賦值等操作。
查看屬性的方法:
[html]
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的實現。

[python] view plain copy
 
 
  1. class Foo(object):  
  2.     def bar(self):  
  3.         print 'Foo.bar'  
  4.   
  5. def bar(self):  
  6.     print 'Modified bar'  
  7.   
  8. Foo().bar()  
  9.   
  10. Foo.bar = bar  
  11.   
  12. 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中查找。這里如果要替換掉一個標准模塊,我們得做以下兩件事情

  1. 將我們自己的module加入到sys.modules中,替換掉原有的模塊。如果被替換模塊還沒加載,那么我們得先對其進行加載,否則第一次加載時,還會加載標准模塊。(這里有一個import hook可以用,不過這需要我們自己實現該hook,可能也可以使用該方法hook module import)
  2. 如果被替換模塊引用了其他模塊,那么我們也需要進行替換,但是這里我們可以修改globals dict,將我們的module加入到globals以hook這些被引用的模塊。

Eventlet Patcher Implementation

現在我們先來看一下eventlet中的Patcher的調用代碼吧,這段代碼對標准的ftplib做monkey patch,將eventlet的GreenSocket替換標准的socket。

[python] view plain copy
 
 
  1. from eventlet import patcher  
  2.   
  3. # *NOTE: there might be some funny business with the "SOCKS" module  
  4. # if it even still exists  
  5. from eventlet.green import socket  
  6.   
  7. patcher.inject('ftplib', globals(), ('socket', socket))  
  8.   
  9. del patcher  

inject函數會將eventlet的socket模塊注入標准的ftplib中,globals dict被傳入以做適當的修改。

讓我們接着來看一下inject的實現。

[python] view plain copy
 
 
  1. __exclude = set(('__builtins__', '__file__', '__name__'))  
  2.   
  3. def inject(module_name, new_globals, *additional_modules):  
  4.     """Base method for "injecting" greened modules into an imported module.  It 
  5.     imports the module specified in *module_name*, arranging things so 
  6.     that the already-imported modules in *additional_modules* are used when 
  7.     *module_name* makes its imports. 
  8.  
  9.     *new_globals* is either None or a globals dictionary that gets populated 
  10.     with the contents of the *module_name* module.  This is useful when creating 
  11.     a "green" version of some other module. 
  12.  
  13.     *additional_modules* should be a collection of two-element tuples, of the 
  14.     form (, ).  If it's not specified, a default selection of 
  15.     name/module pairs is used, which should cover all use cases but may be 
  16.     slower because there are inevitably redundant or unnecessary imports. 
  17.     """  
  18.     if not additional_modules:  
  19.         # supply some defaults  
  20.         additional_modules = (  
  21.             _green_os_modules() +  
  22.             _green_select_modules() +  
  23.             _green_socket_modules() +  
  24.             _green_thread_modules() +  
  25.             _green_time_modules())  
  26.   
  27.     ## Put the specified modules in sys.modules for the duration of the import  
  28.     saved = {}  
  29.     for name, mod in additional_modules:  
  30.         saved[name] = sys.modules.get(name, None)  
  31.         sys.modules[name] = mod  
  32.   
  33.     ## Remove the old module from sys.modules and reimport it while  
  34.     ## the specified modules are in place  
  35.     old_module = sys.modules.pop(module_name, None)  
  36.     try:  
  37.         module = __import__(module_name, {}, {}, module_name.split('.')[:-1])  
  38.   
  39.         if new_globals is not None:  
  40.             ## Update the given globals dictionary with everything from this new module  
  41.             for name in dir(module):  
  42.                 if name not in __exclude:  
  43.                     new_globals[name] = getattr(module, name)  
  44.   
  45.         ## Keep a reference to the new module to prevent it from dying  
  46.         sys.modules['__patched_module_' + module_name] = module  
  47.     finally:  
  48.         ## Put the original module back  
  49.         if old_module is not None:  
  50.             sys.modules[module_name] = old_module  
  51.         elif module_name in sys.modules:  
  52.             del sys.modules[module_name]  
  53.   
  54.         ## Put all the saved modules back  
  55.         for name, mod in additional_modules:  
  56.             if saved[name] is not None:  
  57.                 sys.modules[name] = saved[name]  
  58.             else:  
  59.                 del sys.modules[name]  
  60.   
  61.     return module  

注釋比較清楚的解釋了代碼的意圖。代碼還是比較容易理解的。這里有一個函數__import__,這個函數提供一個模塊名(字符串),來加載一個模塊。而我們import或者reload時提供的名字是對象。

[python] view plain copy
 
 
  1. if new_globals is not None:  
  2.     ## Update the given globals dictionary with everything from this new module  
  3.     for name in dir(module):  
  4.         if name not in __exclude:  
  5.             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。

 

==============================================================================================================================

 

通過 Monkeypatching 更好地測試(Better Debugging through Monkeypatching)

 

模塊 buildbot.test.util.monkeypatches 包含幾個對 Twisted 的monkey-patches,以便更好地檢測錯誤。這些補丁不應該影響正確行為,因此值得在每個測試文件中包含這個:

     from buildbot.test.util.monkeypatches import monkeypatch
     monkeypatch()



這個合成詞兩個部分,就其組成的單個部分而言都是常見詞:monkey(猴子)、patches(補丁);那么 monkey-patches 到底是什么意思呢?

就其詞源(Etymology)來說,這個合成詞應該是一種類似於中文的魯魚亥豕:

據 wikipedia,這個詞似乎來自於guerrilla patch,其意思為,在運行時悄悄地引用改變的代碼。結果 guerrilla(游擊隊) 變成了gorilla(大猩猩), gorilla(大猩猩) 又變成了monkey(猴子) ,其目的似乎是不想叫補丁那么過於引人注目。(錯誤的衍生路線就是:guerrilla(游擊隊)-->因拼法相似誤為gorilla(大猩猩),gorilla(大猩猩)又-->換為同義詞 monkey(猴子),結果,guerrilla patch 就成了monkeypatch(猴子補丁)了)。

這個詞的定義還因所用的上下文而有所不同,在 Python 中,僅僅指在運行時根據補丁的意圖以現有的方法對類進行動態修改,對於一缺陷或者某一不再符合你設計的特征在一外部類中作為一種變通方法。在運行時對一個 類進行修改的其他形式,依據其內容不同有不同的名稱。例如,在 Zope 與 Plone 中安全補丁經常是用動態的類修改進行的,但是它們叫做 hot fixes(熱修改)

在 Ruby 中,意思是對一個類的任何動態修改,常用作在運行時動態修改任何類的同義語。
在中有些人采用duck punching 代替monkey patching,源自於Ruby Python 中動態類型(dynamic typing)的擴充用法。

===============================================================================

轉自:http://www.2cto.com/kf/201211/171518.html

http://blog.csdn.NET/seizef/article/details/5732657

http://complinguistic.blog.sohu.com/166997784.html

http://www.v2ex.com/t/63898


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM