风格:以 `pass` 结束代码块 vs `return`/`continue` vs 无

Style: Ending code blocks with `pass` vs `return`/`continue` vs nothing

python 中的 pass 语句除了填充 space 外什么都不做。但是,我发现在程序继续之前指定一个长而复杂的代码块的结尾很有用:

...
if condition is True:
    ...
    pass
...

本质上,在 C 或 Java.

这样的语言中,与将 } 放在自己的行中的效果相同

同样,我养成了在循环结束时用 continue 替换 pass 的习惯,或者在函数结束时用 return 替换 return 任何东西,出于同样的原因 - 为了更清楚地说明哪个代码块正在结束:

def someFunc():
    ...
    while someCondition is True:
        # complicated things
        ...
        continue
    ...
    return

当代码 spaced 非常狭窄或非常广泛时,或者当代码占据大量垂直 space 时,我认为将这些语句放在代码块的末尾使控制流程更加清晰。我做了一些搜索,但没有找到一个好的来源来说明这是好还是坏的风格(为这个主题制作好的搜索关键字非常困难)。此外,PEP8 对此事只字不提。我希望得到关于这个主题的意见,并找到普遍的共识,如果有的话。

摘自 Robert C. Martin 的“清洁代码”-

The first rule of functions is that they should be small.

The second rule of functions is that they should be smaller than that.

The Zen of Python-

Simple is better than complex.

Readability counts.

在编写代码时,无论使用何种语言,您都应该编写易于阅读和理解的小块代码(方法、循环、if 等)。 通过遵循此规则,您将不会像您提到的那样得到 冗长、复杂的代码块 ,因此需要任何 passcontinuereturn 将消失。

底线

如果您到了要添加这些语句的地步 - 重构您的代码