11

タプルまたは None を返す関数があります。発信者はその状態をどのように処理することになっていますか?

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

またはtry-exceptなし:

res = nontest()

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

どうですか:

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

nontest が本来あるべき 2 項目タプルを返す場合、x と y はタプル内の項目に割り当てられます。それ以外の場合、x と y はそれぞれ none に割り当てられます。これの欠点は、 nontest が空に戻った場合に特別なコードを実行できないことです (それが目標である場合は、上記の回答が役立ちます)。利点は、クリーンで読み取り/保守が容易であることです。

于 2013-07-07T14:18:35.483 に答える