快速背景:寫一個模塊。我的一個對象的方法可能會也可能不會被成功完成 - 這取決於我的模塊下面使用的框架。因此,一些方法首先需要檢查他們實際上在他們腳下的框架。解決這一當前的方法是:導入功能而不是開始或腳本?
def framework_dependent_function():
try:
import module.that.may.not.be.available
except ImportError:
# the required functionality is not available
# this function can not be run
raise WrongFramework
# or should I just leave the previous exception reach higher levels?
[ ... and so on ... ]
丈二和尚在我的腦海裏不斷告訴我,在一個文件的中間做進口是一件壞事。我想,除了稍微雜亂的代碼之外,我不記得原因,甚至不能提出一個理由。
那麼,我在這裏做什麼是否有什麼完全錯誤的?也許還有其他的方式來探索模塊運行在什麼環境,在__init__
附近的某個地方?
這影響了'framework_dependent_function'的第一個定義。 –
@Jakob:你必須在'try'之前放* * def'塊,否則你的'NotImplemented'版本總是會被反彈回到下面的'def'。 –
好點D:。 –