2017-09-19 28 views
0

由於例外對於慣用Python來說非常重要,如果表達式的評估結果爲異常,那麼執行特定代碼塊的乾淨方式是否爲?通過乾淨,我的意思是一個易於閱讀的Pythonic,而不是重複代碼塊?如果條件或異常執行代碼塊

例如,而不是:

try: 
    if some_function(data) is None: 
     report_error('Something happened') 
except SomeException: 
    report_error('Something happened') # repeated code 

可以這樣乾淨改寫,使report_error()不寫了兩次?

(類似的問題:How can I execute same code for a condition in try block without repeating code in except clause但這是在那裏可以通過一個簡單的測試if語句內避免異常的具體情況)

回答

0

是的,這是可以比較乾淨地完成,但它是否能成爲認爲好風格是一個懸而未決的問題。

def test(expression, exception_list, on_exception): 
    try: 
     return expression() 
    except exception_list: 
     return on_exception 

if test(lambda: some_function(data), SomeException, None) is None: 
    report_error('Something happened') 

這來自被拒絕的PEP 463的想法。

lambda to the Rescue提出了相同的想法。