2011-07-06 38 views
3

快速背景:寫一個模塊。我的一個對象的方法可能會也可能不會被成功完成 - 這取決於我的模塊下面使用的框架。因此,一些方法首先需要檢查他們實際上在他們腳下的框架。解決這一當前的方法是:導入功能而不是開始或腳本?

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__附近的某個地方?

回答

3

此版本可能會更快,因爲沒有給函數每次調用需要嘗試import必需的功能:

try: 
    import module.that.may.not.be.available 
    def framework_dependent_function(): 
     # whatever 
except ImportError: 
    def framework_dependent_function(): 
     # the required functionality is not available 
     # this function can not be run 
     raise NotImplementedError 

這也可以讓你做一個嘗試import模塊,然後定義所有那可能不是在一個單一的塊是可用的功能,甚至作爲

def notimplemented(*args, **kwargs): 
    raise NotImplementedError 
fn1 = fn2 = fn3 = notimplemented 

在你的文件的頂部將這個,其他的進口附近,或者在一個單獨的模塊(我目前的項目一個叫utils.fixes)。如果你不喜歡在try/except塊函數定義,然後做

try: 
    from module.that.may.not.be.available import what_we_need 
except ImportError: 
    what_we_need = notimplemented 

如果這些功能必須是方法,那麼你可以將它們添加到您的class後:

class Foo(object): 
    # assuming you've added a self argument to the previous function 
    framework_dependent_method = framework_dependent_function 
1

類似到larsmans建議,但有輕微的變化

def NotImplemented(): 
    raise NotImplementedError 

try: 
    import something.external 
except ImportError: 
    framework_dependent_function = NotImplemented 

def framework_dependent_function(): 
    #whatever 
    return 

我不喜歡的try: except:的函數定義的想法導入

+1

這影響了'framework_dependent_function'的第一個定義。 –

+0

@Jakob:你必須在'try'之前放* * def'塊,否則你的'NotImplemented'版本總是會被反彈回到下面的'def'。 –

+0

好點D:。 –

1

您也可以使用imp.find_module(請參閱here)以檢查是否存在特定的模塊。