考慮下面的包:的的testmod2.py
Python中的條件相對導入...做或不做?
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
內容
這是不好的?有沒有更好的辦法?
我聞到未來的破損和維護問題。我會建議反對它。 – Keith
問題在哪裏? – cdhowie
它在代碼中 - 但要回顧一下:當您直接運行模塊時,相對模塊導入會拋出ValueError,從而無法運行測試代碼。通過添加條件邏輯來檢查模塊是直接運行還是作爲包的一部分導入,它允許我保留直接運行腳本的能力,同時仍然使用相對導入。 – nfarrar