2012-11-27 40 views
1

我還沒有達到我擁有工具(或知道如何開發或使用它們)的水平來測試和分析看似簡單的事情,比如我的問題,所以我轉向你。將模塊導入循環函數中導入?

我有一個函數,檢查一個條件,並根據該條件挑選最佳數學工具(不同的模塊),但該函數應用於數組的窗口,因此是循環的。從窗口到窗口可能會出現不同的導入,但這導致我懷疑導入是否實際上是循環的,並且這完全是性能問題。

下面是從matplotlib源

def pause(interval): 
    """ 
    Pause for *interval* seconds. 

    If there is an active figure it will be updated and displayed, 
    and the GUI event loop will run during the pause. 

    If there is no active figure, or if a non-interactive backend 
    is in use, this executes time.sleep(interval). 

    This can be used for crude animation. For more complex 
    animation, see :mod:`matplotlib.animation`. 

    This function is experimental; its behavior may be changed 
    or extended in a future release. 

    """ 
    backend = rcParams['backend'] 
    if backend in _interactive_bk: 
     figManager = _pylab_helpers.Gcf.get_active() 
     if figManager is not None: 
      canvas = figManager.canvas 
      canvas.draw() 
      show(block=False) 
      canvas.start_event_loop(interval) 
      return 

    # No on-screen figure is active, so sleep() is all we need. 
    import time 
    time.sleep(interval) 

如果我在一個循環中交替打開和關閉數字將時間被導入每隔一個循環的例子?或者剛剛導入第一次導入時被調用並忽略後續導入?

感謝

+0

這一定是一個愚蠢的問題,我被captcha篩選了兩次,第一次輸入了錯誤的一個T_T – arynaq

回答

5

import後成功完成,導入模塊在sys.modules緩存和隨後import報表會發現在sys.modules模塊,使模塊不會重新導入。您可以使用內建函數強制重新導入模塊。

the documentation

第一名導入搜索時檢查是sys.modules。該映射充當先前導入的所有模塊的緩存,包括中間路徑。因此,如果先前導入了foo.bar.baz,則sys.modules將包含foo,foo.barfoo.bar.baz的條目。

PEP 8(Python風格指南)建議導入應位於文件的頂部,而不是方法內。打破這個規則的有效理由(給出一個「後期導入」)是如果一個模塊導入是昂貴的,並且在你的程序中很少使用(並且根本不用於典型的執行),或者解決循環導入依賴你應該嘗試通過更好地分割模塊功能來解決循環)。對於像Python內置的time這樣的模塊,很少有理由使用後期導入。

+0

這使得很多的感覺和很快,謝謝:) – arynaq

1

import的實際操作只發生一次(這就是爲什麼當你確實需要再次導入時需要reload) - 解釋器檢查它是否已經被導入。

但它通常是更多pythonic將所有導入放在模塊的頂部。