关于如何在函数中返回多个值,我看到了很多很好的建议,但是还有什么方法可以处理其他返回,如False?
例如:
def f():
if condition1:
return False
else:
return x, y, z
x, y, z = f()
Run Code Online (Sandbox Code Playgroud)
我可以验证if [x, y, z] is not None:但是如何检查False?它只是if [x, y, z] is not None and f() is not False:或是否有一种优越的方式?
我认为这有助于提高一致性:
def f():
if condition1:
return False, None
else:
return True, (x, y, z)
success, tup = f()
if success:
x, y, z = tup
# use x, y, z...
Run Code Online (Sandbox Code Playgroud)
如果你处于一个不幸的情况,你必须处理一个与你提出的函数类似的函数,一个明确的方法来处理它是一个try:声明.
try:
x, y, z = f()
except TypeError:
<handle the situation where False was returned>
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为尝试解包False提出了一个TypeError.
如果您可以修改该功能,我可能会认为惯用策略是引发错误(内置或自定义)而不是返回False.
def f():
if condition1:
raise ValueError('Calling f() is invalid because condition1 evaluates to True')
return x, y, z
try:
x, y, z = f()
except ValueError:
<handle the situation where a tuple could not be returned>
Run Code Online (Sandbox Code Playgroud)
这有利于在未捕获的回溯中显示错误的真实性质,而不是不那么明显TypeError: 'bool' object is not iterable.它还具有提供一致返回类型的好处,因此不会产生用户混淆.
文档也变得更加清晰,因为而不是
"in the case of success it will return a tuple of three elements, but in the case of failure it will return False (not as a tuple)"
Run Code Online (Sandbox Code Playgroud)
文档变成了
"returns a tuple of three elements; raises a ValueError on failure"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1424 次 |
| 最近记录: |