2013-05-08 31 views
1

我在Python中有一個類函數,可以返回成功或失敗,但如果發生故障,我希望它發回特定的錯誤字符串。我心裏有3種方法:從Python中的函數返回錯誤字符串

  1. 傳遞一個變量ERROR_MSG到最初設置爲無,在一個錯誤的情況下,它被設置爲錯誤字符串的函數。例如:

    if !(foo(self, input, error_msg)): 
        print "no error" 
    else: 
        print error_msg 
    
  2. 返回包含函數的bool和error_msg的元組。

  3. 我在發生錯誤時引發異常並在調用代碼中捕獲它。但是由於我沒有看到我正在使用的代碼庫中經常使用異常,所以不太確定採用這種方法。

什麼是Pythonic這樣做?

+2

爲什麼不例外? – 2013-05-08 22:50:57

回答

8

創建自己的異常,並提高該相反:

class MyValidationError(Exception): 
    pass 

def my_function(): 
    if not foo(): 
     raise MyValidationError("Error message") 
    return 4 

然後,您可以調用你的函數爲:

try: 
    result = my_function() 
except MyValidationError as exception: 
    # handle exception here and get error message 
    print exception.message 

這種風格被稱爲EAFP(「易請求原諒比許可」 )這意味着你寫的代碼是正常的,出現異常時會引發異常,並在稍後處理:

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

5

引發錯誤:

if foo(self, input, error_msg): 
    raise SomethingError("You broke it") 

而且處理:

try: 
    something() 
except SomethingError as e: 
    print str(e) 

這是Python的方法和最可讀的。

返回像(12, None)這樣的元組可能看起來是一個很好的解決方案,但如果不一致,很難跟蹤每種方法的返回結果。返回兩種不同的數據類型更糟糕,因爲它可能會破壞假定數據類型不變的代碼。