python中的猴子補丁Monkey Patch
什么是猴子補丁
the term monkey patch only refers to dynamic modifications of a class or module at runtime, motivated by the intent to patch existing third-party code as a workaround to a bug or feature which does not act as desired
即在運行時對方法 / 類 / 屬性 / 功能進行修改,把新的代碼作為解決方案代替原有的程序,也就是為其打上補丁。
為什么叫做猴子補丁
The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily – and possibly incompatibly with other such patches – at runtime.The word guerrilla, homophonous with gorilla (or nearly so), became monkey, possibly to make the patch sound less intimidating.[1] An alternative etymology is that it refers to “monkeying about” with the code (messing with it).
- 一種說法雜牌軍、游擊隊的英文發音與猩猩相似,雜牌軍、游擊隊不是原裝軍隊,就像是替補,所以也就演變叫做猴子補丁
- 另一種說法“monkeying about”有胡鬧,頑皮,哄騙的意思,所以叫做猴子補丁
python中使用猴子補丁
class Example():
def func1(self):
print('我才是原裝')
def func2(*args):
print('我要取代你')
def func3(*args):
print('都給我一邊去')
instance = Example()
Example.func1 = func2
instance.func1() # 我要取代你
instance.func1 = func3
instance.func1() # 都給我一邊去
instance2 = Example()
instance2.func1() # 我要取代你
例子非常簡單,func2取代的是類的方法,func3取代的是實例的方法,最終輸出都不是原裝
其他例子
在使用gevent模塊的使用就會遇到猴子補丁
import gevent.monkey
gevent.monkey.patch_all()
使用猴子補丁的方式,gevent能夠修改標准庫里面大部分的阻塞式系統調用,包括socket、ssl、threading和 select等模塊,而變為協作式運行。也就是通過猴子補丁的monkey.patch_xxx()來將python標准庫中模塊或函數改成gevent中的響應的具有協程的協作式對象。這樣在不改變原有代碼的情況下,將應用的阻塞式方法,變成協程式的。
這里參考https://blog.csdn.net/wangjianno2/article/details/51708658
注意問題
在使用猴子補丁的時候同樣容易出現問題
- 當進行版本更新變化的時候,很容易對補丁做出破壞
- 不知情的情況下對一個位置打兩個補丁會造成替換
- 對於不知道有補丁的人來說可能會對出現的某些情況感到困惑