在 Python 中使用 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
”?