2012-07-29 93 views
1

我有Python中的函數,它在一根繩子上的錯誤檢查。如果函數發現錯誤,它將返回一個包含錯誤代碼和該錯誤標識符的元組。在程序的後面,我有處理錯誤的功能。它接受元組爲兩個變量。元組在缺失值

errCode, i = check_string(s,pathType) 

check_string是產生元組的函數。如果沒有錯誤,我希望它做的只是返回零。當返回零時,上面的代碼似乎失敗了,因爲變量i沒有任何內容。

有沒有一種簡單的方法來得到這個工作,或者我只需要程序返回一個0和0的元組,如果沒有發現錯誤?

回答

3

我會爲此使用異常系統。

class StringError(Exception): 
    NO_E = 0 
    HAS_Z = 1 

def string_checker(string): 
    if 'e' not in string: 
     raise StringError('e not found in string', StringError.NO_E) 
    if 'z' in string: 
     raise StringError('z not allowed in string', StringError.HAS_Z) 
    return string.upper() 

s = 'testing' 
try: 
    ret = string_checker(s) 
    print 'String was okay:', ret 
except StringError as e: 
    print 'String not okay with an error code of', e.args[1] 
+1

也許我沒有得到這個問題,但是這一切只需檢查元組是否包含一個或兩個值? *不是*意味着批評,顯然使用異常機制有其地位(EAFP),但似乎比必要的更復雜。 – Levon 2012-07-29 10:52:52

+1

@Levon返回錯誤值相當於C-ish而不是非常Pythonic。也許我在這兩行之間讀了太多內容,但考慮到OP的第一段,我的第一個想法是「使用異常」 - 在這種情況下,'string_checker'返回一個有效的字符串(不使用元組和代碼),否則引發,可以在任何需要的地方進行處理......對我來說似乎只是一種「更清潔」的設計。 – 2012-07-29 10:58:44

+0

欣賞反饋,我看到你的推理,謝謝。 – Levon 2012-07-29 11:00:12

1

爲什麼不只是試圖檢索值前檢查數組的長度是多少?

err_tup = check_String(s, pathType) 
if len(err_tup) == 2: 
    errCode, i = err_tup 
else: # assuming it can only be 1 otherwise 
    errCode = err_tup 

這將工作,而不會對生成元組的其餘代碼進行任何更改,並且語義清晰。

基於「簡單勝過複雜」。

1

您可以使用無作爲值誤差

def check_string(s,pathType): 
    # No error 
    return (None, i) 
0

如果你要返回零:

foo = func() 
if not foo: 
    print 'No errors' 
else: 
    # foo is tuple