0

I have one function (F1) returning the values of (a, b, c) and other function (F2) using those values. I need to check on F2 if "a is None".

This is the first function (F1)

def get_info():
   msg = get_msg()
   number = get_number()
   if msg is not None:
      return msg, number
   return False, False

Secound function (F2)

def save_log():
   msg, number = get_info()
   if msg:
      do_more_stuff

If I don't do return False, False in the first function I get TypeError: 'bool' object is not iterable in the second function. Do I have a better way of returning those values other than return False, False.

What is the pythonic best practice in this situation? Thanks

4

1 回答 1

0

这就是使用错误/异常的解决方案的样子。 get_msgget_number如果适用的话)会在它们未能返回值时引发异常,而不是返回指示失败的值。

class MessageRetrievalError(Exception):
    pass

def get_msg():
    message = message_code()
    if message is None:
        raise MessageRetrievalError
    return message

def get_info():
    return get_msg(), get_number()

def save_log():
    try:
        msg, number = get_info()
        do_more_stuff
    except MessageRetrievalError:
        do_other_stuff
于 2018-11-08T18:48:44.877 回答