简体   繁体   中英

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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM