python - 嵌套 if 子句 vs 级联返回 vs 断言

标签 python if-statement control-flow

当 if 子句中的负评估将导致函数/方法内部的 return 调用时,Python 中更推荐的是嵌套 if 子句或利用逆评估并调用函数 return ?例如:

if required_condition_1:
    if required_condition_2:
        if required_condition 3:
            pass
        return 'error for condition 3'
    return 'error for condition 2'
return 'error for condition 1'

或者:

if not required_condition_1:
    # preparation...
    return 'error for condition 1'

if not required_condition_2:
    # preparation...
    return 'error for condition 2'

if not required_condition_3:
    # preparation...
    return 'error for condition 3'

# if runtime reaches this point it means that it has passed all conditions

假设您必须注册一个用户,并且需要满足各种条件。用户只有在他们都满意的情况下才会被注册,但错误消息取决于失败的条件。

我的猜测是,在其他情况下,正如用户在答案部分提到的那样,如果特定条件失败,则可以应用其他操作。然后我想我应该嵌套ifs。但是,我只会返回一条错误消息,所以我认为第二种选择更可取。

我也想过断言:

try:
    assert(required_condition_1)
    try:
        assert(required_condition_2)
        # do tasks
    except AssertionError:
        # error for condition 2
except AssertionError:
    # error for condition 1

尽管我认为最后一种方法在处理异常时不太值得推荐。也是 SO 用户 mentions :

If the code is correct, barring Single-event upsets, hardware failures and such, no assert will ever fail. That is why the behaviour of the program to an end user must not be affected. Especially, an assert cannot fail even under exceptional programmatic conditions. It just doesn't ever happen. If it happens, the programmer should be zapped for it.

我知道这可能看起来主要是基于意见,但对我来说它不是,因为所有语言都有风格指南,可以产生更可持续、可扩展和可读的环境,具体取决于关于它的特点和功能。我想知道是否有推荐的方法在方法中处理这个问题,最重要的是,为什么

最佳答案

虽然这可以被视为基于意见,但我认为客观上第二种方式似乎更具可读性。

在您的第一个示例中,阅读您的代码的人必须解密每个语句与其嵌套的语句在逻辑上不相关,这是您不希望发生的事情。一般来说,嵌套 block 意味着某种继承逻辑。

第二个例子写得更简洁,不需要太多思考就可以实现逻辑流程。逻辑流程似乎暗示无论如何都应该满足每个条件,而不是越走越深您想要应用的条件。

第一种风格有其用例,只是不适用于手头的给定任务:条件检查。


关于您的第二个问题,在此用例中使用断言将被认为是不合适的。根据经验,只有在永远不会出错但对程序执行非常重要的事情出错时才使用断言。最明显的用途之一是编写测试用例,一个函数应该给出一定的输出,如果它不给你那个输出就非常糟糕。

异常是指您可能预计会出错的事情例如除以零错误、属性错误等处理用户输入时的错误。

关于python - 嵌套 if 子句 vs 级联返回 vs 断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47972114/

相关文章:

python - Scrapy:无法创建项目

python - sqlite3、Python中 "="和 "match"之间的区别?

java - 关于Java lang中的if语句

c# - IEnumerable foreach,对最后一个元素做一些不同的事情

python - 重复模式,包含的 django url 中的名称不同

shell - 我如何比较shell中的2个字符串?

sql - COUNT DISTINCT WITH CONDITION 和 GROUP BY

SSIS 控制流 : Wait till all tasks complete

python - 避免 Python 代码中的代码重复

python - 使用请求正文的单元测试 bottle py 应用程序导致 KeyError : 'wsgi.input'