[英]How to create optional tuple return or unpack
I want to send tuple back if function returns error message and the data if success:如果函数返回错误消息,我想将元组发送回,如果成功则返回数据:
Example function:示例函数:
def test(args):
if (some success here):
return data
return None, error_message
Call:称呼:
data, error_msg = test(args)
if error_msg:
return somehttpresponse(error_msg, 400)
return somehttpresponse(data, 200)
How can I achieve this in python?我怎样才能在 python 中实现这一点? Or is there any other clean way to return error message without compromising the return data on success?
或者有没有其他干净的方法来返回错误消息而不影响成功的返回数据?
So far I used Exception:到目前为止,我使用了异常:
Example function:示例函数:
def test(args):
if (some success here):
return data
raise ValueError(error_message)
return None
Call:称呼:
try:
data = test(args)
return somehttpresponse(data, 200)
except ValueError as err:
return somehttpresponse(err, 400)
Not sure if it's the most efficient way.不确定这是否是最有效的方法。 still hoping someone has an answer
仍然希望有人有答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.