有时我会把if中的长条件分解成几行。最明显的方法是:

  if (cond1 == 'val1' and cond2 == 'val2' and
      cond3 == 'val3' and cond4 == 'val4'):
      do_something

视觉上不是很吸引人,因为动作与环境融为一体。然而,这是使用4个空格的正确Python缩进的自然方式。

目前我正在使用:

  if (    cond1 == 'val1' and cond2 == 'val2' and
          cond3 == 'val3' and cond4 == 'val4'):
      do_something

但这不是很漂亮

你能推荐另一种方法吗?


当前回答

我通常做的是:

if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'
   ):
    do_something

这样,右括号和冒号可视地标志着我们的状态结束。

其他回答

似乎值得引用PEP 0008(Python的官方风格指南),因为它对这个问题的评论篇幅适中:

如果if语句的条件部分足够长,需要跨多行编写,那么值得注意的是,两个字符的关键字(即if)加上一个空格和一个左括号的组合会为多行条件语句的后续行创建一个自然的4空格缩进。这可能会与嵌套在if语句中的缩进代码集产生视觉冲突,这也会自然缩进到4个空格。对于如何(或是否)进一步从视觉上区分if语句中的嵌套套件和这些条件行,PEP没有明确的立场。这种情况下可接受的选项包括但不限于:#无额外压痕。如果(this_is_one_thing和that_is_aother_thing):do_something()#添加注释,这将在编辑器中提供一些区别#支持语法高亮显示。如果(this_is_one_thing和that_is_aother_thing):#既然这两个条件都成立,我们就可以结婚了。do_something()#在条件延续行上添加一些额外的缩进。如果(this_is_one_thing和that_is_aother_thing):do_something()

请注意上述报价中的“不限于”;除了风格指南中建议的方法外,其他问题答案中建议的一些方法也是可以接受的。

我通常使用:

if ((cond1 == 'val1' and cond2 == 'val2' and
     cond3 == 'val3' and cond4 == 'val4')):
    do_something()

我知道这个线程很旧,但我有一些Python 2.7代码,PyCharm(4.5)仍然抱怨这个例子:

if foo is not None:
    if (cond1 == 'val1' and cond2 == 'val2' and
        cond3 == 'val3' and cond4 == 'val4'):
            # some comment about do_something
            do_something

即使有PEP8警告“视觉缩进的行与下一个逻辑行缩进相同”,实际代码也完全正常?这不是“过度缩进?”

……有时我希望Python能咬紧牙关,只带上大括号。我想知道这些年来有多少错误是由于错误的缩进而被意外引入的。。。

加上@krawyoti所说的。。。长时间的环境气味难闻,因为它们难以阅读和理解。使用函数或变量可以使代码更清晰。在Python中,我更喜欢使用垂直空格,括起括号,并将逻辑运算符放在每一行的开头,这样表达式看起来不像“浮动”。

conditions_met = (
    cond1 == 'val1' 
    and cond2 == 'val2' 
    and cond3 == 'val3' 
    and cond4 == 'val4'
    )
if conditions_met:
    do_something

如果需要对条件进行多次求值,例如在while循环中,那么最好使用局部函数。

我发现当我有长条件时,我通常有一个短代码体。在这种情况下,我只需将主体缩进两次,这样:

if (cond1 == 'val1' and cond2 == 'val2' and
    cond3 == 'val3' and cond4 == 'val4'):
        do_something