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