从显式返回False的函数中接收None

时间:2017-03-23 15:18:14

标签: python

我有一个迭代测试并执行它们的函数。在执行每个测试之前,它会调用函数confirm_execute()来检查测试是否已被取消。 confirm_execute()如下所示(原谅调试消息的混乱):

def confirm_execute(self):
    self._update_hil_status()
    status = self.hil_status['status']
    print 'STATUS =', status

    if status == 'TESTING':
        return True
    elif status == 'CANCEL':
        print '##### Cancelling #####'
        return False

    elif status == 'REQUEST_STOP':
        print '##### Stopping tests #####'
        self._set_hil_status(status='STOPPED')
    elif status == 'STOPPED':
        time.sleep(5)
    elif status == 'RESUME':
        print '##### Resuming tests #####'
        self._set_hil_status(status='TESTING')
    else:
        print '##### Invalid status {} - setting stop status #####'.format(status)
        self._set_hil_status(status='STOPPED')

    self.confirm_execute()  # only exit if status is testing or cancel

在执行测试之前检查权限的函数部分在这里:

allow = self.status.confirm_execute()
if allow:
    print 'continue: {}'.format(allow)
    # run a test
else:
    print 'cancel: {}'.format(allow)
    # clean up

问题在于:当我将status设置为CANCEL时,confirm_execute似乎返回None而不是False。当我停止一组测试然后尝试取消时,这是控制台上的输出:

STATUS = REQUEST_STOP
##### Stopping tests #####
SETTING STOPPED
STATUS = STOPPED
STATUS = STOPPED
STATUS = CANCEL
##### Cancelling #####
cancel: None

请注意,我收到##### Cancelling #####消息,这意味着我应该返回False。但是,allow收到的值似乎为None

我犯了什么简单的错误?

2 个答案:

答案 0 :(得分:3)

您的函数仅显式返回TESTINGCANCEL的值。 否则它只是打印东西,调用自身,并没有明确地返回任何东西。这意味着它隐式返回None

你想要的是return self.confirm_execute()

答案 1 :(得分:3)

此处递归不是合适的解决方案。每次结果都不是CANCEL或TESTING时,函数会调用自身;但是你没有从这些嵌套调用返回值,因此它们会丢失。

您应该将整个函数放在while True循环中,而不是递归,因此它将继续循环,直到达到其中一个返回案例。