python Monkey patch

What is Monkey Patch

Monkey Patch 就是在運行時對已有的代碼進行修改,達到hot patch的目的。Eventlet中大量使用了該技巧,以替換標準庫中的組件,好比socket。首先來看一下最簡單的monkey patch的實現。python

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的目的。socket

Python namespace

Python有幾個namespace,分別是函數

  • locals
  • globals
  • builtin

其中定義在函數內聲明的變量屬於locals,而模塊內定義的函數屬於globals。ui

Python module Import & Name Lookup

當咱們import一個module時,python會作如下幾件事情this

  • 導入一個module
  • 將module對象加入到sys.modules,後續對該module的導入將直接從該dict中得到
  • 將module對象加入到globals dict中

當咱們引用一個模塊時,將會從globals中查找。這裏若是要替換掉一個標準模塊,咱們得作如下兩件事情spa

  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。code

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被傳入以作適當的修改。orm

讓咱們接着來看一下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時提供的名字是對象。ci

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。

相關文章
相關標籤/搜索