11

我有一个返回元组或无的函数。呼叫者应该如何处理这种情况?

def nontest():
  return None

x,y = nontest()

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
4

3 回答 3

11

EAFP

try:
    x,y = nontest()
except TypeError:
    # do the None-thing here or pass

或没有尝试除外:

res = nontest()

if res is None:
    ....
else:
    x, y = res
于 2013-05-14T01:22:54.950 回答
8

怎么样:

x,y = nontest() or (None,None)

如果 nontest 返回一个包含两项的元组,则将 x 和 y 分配给元组中的项。否则,x 和 y 将分别赋值为 none。不利的一面是,如果非测试返回为空,您将无法运行特殊代码(如果这是您的目标,上述答案可以帮助您)。好处是它干净且易于阅读/维护。

于 2013-07-07T14:18:35.483 回答
5

如果您可以更改函数本身,最好让它引发相关异常,而不是返回None以指示错误条件。然后调用者应该只是try/except那个。

如果None 没有发出错误信号,您将需要重新考虑您的语义。

于 2013-05-14T01:31:27.783 回答