在Python中使用class作爲特殊值是否難看?使用class作爲特殊值?
考慮一下:
def find_result():
result = None
# do something to find the result, even recursing
return result
r = find_result()
if r is None:
raise Exception("we have no result")
這工作完全,如果我希望結果是數字,或任何「正常」的類型。
但是如果有一個任意的數據結構,結果可以是從None
到另一個結構的任何東西?我在我的情況確實是這樣的:
class NoResult:
"""i'm even less than `None`."""
pass
def query(data, path):
result = NoResult
# traverse and recurse into the data structure
return result
r = query()
if r is NoResult:
raise Exception("our hands are empty")
它的工作原理,但我不能動搖,我是一個有點濫用這裏的貧困階層,感覺和甚至有可能是一個真正的危險潛伏內。
這是真的嗎?我濫用課堂嗎?或者只是我的算法很糟糕,如果它需要依賴像這樣的「特殊None
」?
爲什麼不在'find_result'中引發異常而不是返回任何東西?引發異常的整個想法是提供一種獨立於識別特殊返回值的替代錯誤檢測機制。 – chepner
@chepner我是這樣做的,因爲我需要更深入地遞歸,並且我從來不知道我想停止搜索直到回到頂部的電話。現在我想到了,也許通過適當的異常處理,它可能會更好...... –