2011-08-25 56 views
2

考慮下面的包:的的testmod2.pyPython中的條件相對導入...做或不做?

if __name__ == 'testpackage.testmod2': 
    from . import testmod 
else: 
    import testmod 
... 
if __name__ == '__main__': 
    # test code here, will execute when the file is run directly 
    # due to conditional imports 

# relative import without conditional logic, breaks when run directly 
from . import testmod2 
... 
if __name__ == '__main__': 
    # do my module testing here 
    # this code will never execute since the relative import 
    # always throws an error when run directly 

內容__init__.py

from . import testmod 
from . import testmod2 

內容

testpackage 
    __init__.py 
    testmod.py 
    testmod2.py 

內容

這是不好的?有沒有更好的辦法?

+0

我聞到未來的破損和維護問題。我會建議反對它。 – Keith

+2

問題在哪裏? – cdhowie

+0

它在代碼中 - 但要回顧一下:當您直接運行模塊時,相對模塊導入會拋出ValueError,從而無法運行測試代碼。通過添加條件邏輯來檢查模塊是直接運行還是作爲包的一部分導入,它允許我保留直接運行腳本的能力,同時仍然使用相對導入。 – nfarrar

回答

1

這肯定會成爲未來的維護頭痛。不只是有條件的進口...更多的原因爲什麼你不得不做的有條件的進口,即運行testpackage/testmod2.py作爲主要腳本導致第一項sys.path./testpackage而不是.,這使得它的存在測試包作爲包走開。

相反,我建議通過python -m testpackage.testmod2運行testmod2,並從外部執行testpackagetestpackage.testmod2仍然會顯示爲__main__,但有條件的導入將始終有效,因爲testpackage將始終是一個包。

-m捕捉是它需要Python 2.5 or newer

+0

我直接運行模塊的唯一原因是測試/調試。在VIM中,我將 -e綁定爲直接執行當前的python文件 - 我將其添加到模塊時不斷用於測試代碼。也許更好的解決方案是創建一個自定義的vim​​文件,當使用上面引用的-m標誌加載執行該模塊的項目時,我會獲得該文件。 – nfarrar