Monkey Patch猴子補丁方式是指在不修改程式原本程式碼的前提下,透過添加類別或模組等方式在程式運行過程中加入程式碼,下面就來進一步詳解Python程式設計中對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 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程式中對Monkey Patch猴子補丁開發方式相關文章請關注PHP中文網!
#

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

如何解決jieba分詞在景區評論分析中的問題?當我們在進行景區評論分析時,往往會使用jieba分詞工具來處理文�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載
最受歡迎的的開源編輯器

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器