在 Python 中使用类作为特殊值是不是很丑陋?
考虑一下:
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")
它有效,但我无法摆脱我有点虐待这里可怜的类(class)的感觉,甚至可能潜伏着真正的危险。
这是真的吗?我在滥用类吗?或者,如果我的算法需要依赖像这样的“特殊None
”,它就很糟糕?
最佳答案
它被称为哨兵,你可以为它使用任何独特的对象:
sentinel = object()
if r is sentinel:
raise Exception(..)
这里我使用了一个简单的 object()
实例而不是自定义类。
自定义类确实有一个优势,它可能更自文档化;如果您的 API 必须将对象传递给 API 的用户(可以是代码),那么显式类更好。对于仅在 API 的黑盒中使用,object()
就可以了。
你可能想考虑在你现在返回哨兵的地方引发异常。您总是可以再次捕获异常。
关于python - 使用类作为特殊值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19159684/