返回 None 或元组并解包 [英] Returning None or a tuple and unpacking
问题描述
我总是对这个事实感到恼火:
I am always annoyed by this fact:
$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
事实是,为了正确解包而不会遇到麻烦,我必须捕获 TypeError 或具有类似的东西
The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like
values = foo(False)
if values is not None:
first, second = values
这有点烦人.是否有改善这种情况的技巧(例如,将 first 和 second 都设置为 None 而没有 foo 返回(None,None))或有关我提出的案例的最佳设计策略的建议?*可能是变量?
Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? *variables maybe ?
推荐答案
好吧,你可以...
first,second = foo(True) or (None,None)
first,second = foo(False) or (None,None)
但据我所知,没有更简单的方法可以扩展 None 来填充整个元组.
but as far as I know there's no simpler way to expand None to fill in the entirety of a tuple.
这篇关于返回 None 或元组并解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!