最好的做法是在Python if或if / elif语句的末尾包含else:pass语句吗? [英] Is it best practice to include an else: pass statement at the end of a Python if or if/elif statement?

查看:2786
本文介绍了最好的做法是在Python if或if / elif语句的末尾包含else:pass语句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写:

if a == b:
    # do something
elif a == c:
    # do something else

我只是想通过其他方式,是在结尾写出以下要求?:

and I just want to pass otherwise, is writing out the following required at the end?:

else:
    pass

在没有解释器中的 else:语句的情况下似乎运行良好,是否存在我不知道我应该总是包括否则:在这些情况下传递

It seems to run fine without the else: statement in the interpreter, is there a reason I'm not aware of that I should always include else: pass in these cases?

推荐答案

不,不是, else 套件完全是可选的。

No, it isn't, the else suite is entirely optional.

来自 if 声明文档

From the if statement documentation:


if_stmt ::=  "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]


其中(...)* 表示零或更多 [...] 表示可选。所以有效的 if 复合语句有一个如果行和套件,0或更多 elif 行和相应的套件,最多一个 else 行和套件,这是可选的。

where (...)* means zero or more, and [...] means optional. So a valid if compound statement has an if line and suite, 0 or more elif lines and corresponding suites, and at most one else line and suite, which is optional.

Python编译器将忽略任何 else:pass 块,包含它真的没有意义:

The Python compiler will ignore any else: pass block, there is really no point in including it:

>>> import dis
>>> dis.dis(compile('''\
... if True:
...     foo
... else:
...     pass
... ''', '<stdin>', 'exec'))
  1           0 LOAD_NAME                0 (True)
              3 POP_JUMP_IF_FALSE       13

  2           6 LOAD_NAME                1 (foo)
              9 POP_TOP             
             10 JUMP_FORWARD             0 (to 13)

  4     >>   13 LOAD_CONST               0 (None)
             16 RETURN_VALUE        
>>> dis.dis(compile('''\
... if True:
...     foo
... ''', '<stdin>', 'exec'))
  1           0 LOAD_NAME                0 (True)
              3 POP_JUMP_IF_FALSE       13

  2           6 LOAD_NAME                1 (foo)
              9 POP_TOP             
             10 JUMP_FORWARD             0 (to 13)
        >>   13 LOAD_CONST               0 (None)
             16 RETURN_VALUE        

其中唯一的区别是附加的行号到 LOAD_CONST 字节码,因为第一个源样本中有额外的行。

where the only difference is the line number attached to the LOAD_CONST bytecode because of the extra lines in the first source sample.

在风格上, else:传递只是混乱,是为了降低可读性。

Stylistically, else: pass is just clutter, something to reduce readability.

这篇关于最好的做法是在Python if或if / elif语句的末尾包含else:pass语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆