最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Python編程中對Monkey Patch猴子補(bǔ)丁開發(fā)方式的運(yùn)用

 更新時間:2016年05月27日 19:02:37   作者:有心故我在  
Monkey Patch猴子補(bǔ)丁方式是指在不修改程序原本代碼的前提下,通過添加類或模塊等方式在程序運(yùn)行過程中加入代碼,下面就來進(jìn)一步詳解Python編程中對Monkey Patch猴子補(bǔ)丁開發(fā)方式的運(yùn)用

Monkey patch就是在運(yùn)行時對已有的代碼進(jìn)行修改,達(dá)到hot patch的目的。Eventlet中大量使用了該技巧,以替換標(biāo)準(zhǔn)庫中的組件,比如socket。首先來看一下最簡單的monkey patch的實(shí)現(xiàn)。

class Foo(object):
  def bar(self):
    print 'Foo.bar'

def bar(self):
  print 'Modified bar'

Foo().bar()

Foo.bar = bar

Foo().bar()

由于Python中的名字空間是開放,通過dict來實(shí)現(xiàn),所以很容易就可以達(dá)到patch的目的。

Python namespace

Python有幾個namespace,分別是

  • locals
  • globals
  • builtin

其中定義在函數(shù)內(nèi)聲明的變量屬于locals,而模塊內(nèi)定義的函數(shù)屬于globals。

Python module Import & Name Lookup

當(dāng)我們import一個module時,python會做以下幾件事情

  • 導(dǎo)入一個module
  • 將module對象加入到sys.modules,后續(xù)對該module的導(dǎo)入將直接從該dict中獲得
  • 將module對象加入到globals dict中

當(dāng)我們引用一個模塊時,將會從globals中查找。這里如果要替換掉一個標(biāo)準(zhǔn)模塊,我們得做以下兩件事情

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

現(xiàn)在我們先來看一下eventlet中的Patcher的調(diào)用代碼吧,這段代碼對標(biāo)準(zhǔn)的ftplib做monkey patch,將eventlet的GreenSocket替換標(biāo)準(zhǔn)的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函數(shù)會將eventlet的socket模塊注入標(biāo)準(zhǔn)的ftplib中,globals dict被傳入以做適當(dāng)?shù)男薷摹?

讓我們接著來看一下inject的實(shí)現(xiàn)。

__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

注釋比較清楚的解釋了代碼的意圖。代碼還是比較容易理解的。這里有一個函數(shù)__import__,這個函數(shù)提供一個模塊名(字符串),來加載一個模塊。而我們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)

這段代碼的作用是將標(biāo)準(zhǔn)的ftplib中的對象加入到eventlet的ftplib模塊中。因?yàn)槲覀冊趀ventlet.ftplib中調(diào)用了inject,傳入了globals,而inject中我們手動__import__了這個module,只得到了一個模塊對象,所以模塊中的對象不會被加入到globals中,需要手動添加。
這里為什么不用from ftplib import *的緣故,應(yīng)該是因?yàn)檫@樣無法做到完全替換ftplib的目的。因?yàn)閒rom … import *會根據(jù)__init__.py中的__all__列表來導(dǎo)入public symbol,而這樣對于下劃線開頭的private symbol將不會導(dǎo)入,無法做到完全patch。

相關(guān)文章

  • 詳談tensorflow gfile文件的用法

    詳談tensorflow gfile文件的用法

    今天小編就為大家分享一篇詳談tensorflow gfile文件的用法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • Python制作進(jìn)度條的四種方法總結(jié)

    Python制作進(jìn)度條的四種方法總結(jié)

    如果你之前沒用過進(jìn)度條,八成是覺得它會增加不必要的復(fù)雜性或者很難維護(hù),其實(shí)不然。要加一個進(jìn)度條其實(shí)只需要幾行代碼,快跟隨小編一起學(xué)習(xí)學(xué)習(xí)吧
    2022-11-11
  • 基于Python實(shí)現(xiàn)一個春節(jié)倒計(jì)時腳本

    基于Python實(shí)現(xiàn)一個春節(jié)倒計(jì)時腳本

    春節(jié)即將到來,本文將為大家介紹一個通過Python實(shí)現(xiàn)的春節(jié)倒計(jì)時腳本,文中的示例代碼簡潔易懂,感興趣的小伙伴可以自己動手嘗試一下
    2022-01-01
  • pandas中對文本類型數(shù)據(jù)的處理小結(jié)

    pandas中對文本類型數(shù)據(jù)的處理小結(jié)

    這篇文章主要介紹了pandas中對于文本類型數(shù)據(jù)的處理匯總,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-11-11
  • Python數(shù)據(jù)分析庫pandas高級接口dt的使用詳解

    Python數(shù)據(jù)分析庫pandas高級接口dt的使用詳解

    這篇文章主要介紹了Python數(shù)據(jù)分析庫pandas高級接口dt的使用詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • Pandas格式化DataFrame的浮點(diǎn)數(shù)列的實(shí)現(xiàn)

    Pandas格式化DataFrame的浮點(diǎn)數(shù)列的實(shí)現(xiàn)

    本文主要介紹了Pandas格式化DataFrame的浮點(diǎn)數(shù)列的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-05-05
  • 在Python中os.fork()產(chǎn)生子進(jìn)程的例子

    在Python中os.fork()產(chǎn)生子進(jìn)程的例子

    今天小編就為大家分享一篇在Python中os.fork()產(chǎn)生子進(jìn)程的例子,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Python tkinter模塊中類繼承的三種方式分析

    Python tkinter模塊中類繼承的三種方式分析

    這篇文章主要介紹了Python tkinter模塊中類繼承的三種方式,結(jié)合實(shí)例形式分析了三種繼承方式的實(shí)現(xiàn)方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2017-08-08
  • 詳解使用Selenium爬取豆瓣電影前100的愛情片相關(guān)信息

    詳解使用Selenium爬取豆瓣電影前100的愛情片相關(guān)信息

    這篇文章主要介紹了詳解使用Selenium爬取豆瓣電影前100的愛情片相關(guān)信息,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • Python利用pyreadline模塊實(shí)現(xiàn)交互式命令行開發(fā)

    Python利用pyreadline模塊實(shí)現(xiàn)交互式命令行開發(fā)

    交互式命令行是一種方便用戶進(jìn)行交互的工具,能夠使用戶與計(jì)算機(jī)進(jìn)行快速的交互操作,提高工作效率。本文主要介紹了如何利用pyreadline模塊實(shí)現(xiàn)交互式命令行開發(fā),需要的可以參考一下
    2023-05-05

最新評論

乐清市| 松桃| 卫辉市| 开化县| 静宁县| 同德县| 北票市| 汾阳市| 乾安县| 文登市| 宣威市| 齐河县| 安平县| 昭觉县| 上杭县| 东台市| 安岳县| 宜都市| 革吉县| 襄城县| 鸡东县| 自贡市| 兴国县| 葵青区| 巴塘县| 彰武县| 肥东县| 莒南县| 萍乡市| 秭归县| 桂平市| 福建省| 海口市| 南宫市| 宽甸| 十堰市| 道孚县| 绥宁县| 义乌市| 手游| 石楼县|