有时我会把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

或者如果这更清楚:

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

在这种情况下,缩进不应该是4的倍数,例如,请参见“与开头分隔符对齐”:

http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Indentation#Indentation

其他回答

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

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

这里必须有人支持使用垂直空格!:)

if (     cond1 == val1
     and cond2 == val2
     and cond3 == val3
   ):
    do_stuff()

这使每个条件都清晰可见。它还允许更清晰地表达更复杂的条件:

if (    cond1 == val1
     or 
        (     cond2_1 == val2_1
          and cond2_2 >= val2_2
          and cond2_3 != bad2_3
        )
   ):
    do_more_stuff()

是的,为了清晰起见,我们在交易一些垂直房地产。非常值得。

这没有多大改善,但。。。

allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
                 cond3 == 'val3' and cond4 == 'val4')

if allCondsAreOK:
   do_something

(我对标识符进行了轻微修改,因为固定宽度的名称不能代表真实代码——至少不能代表我遇到的真实代码——并且会掩盖示例的可读性。)

if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4"):
    do_something

这适用于“和”和“或”(重要的是它们位于第二行的第一位),但对于其他较长的条件就更不适用了。幸运的是,前者似乎是更常见的情况,而后者往往很容易用临时变量重写。(这通常不难,但在重写时保持“和”/“或”的短路可能很难或不那么明显/可读。)

由于我在你的关于C++的博客文章中发现了这个问题,我将补充我的C++风格是相同的:

if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "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能咬紧牙关,只带上大括号。我想知道这些年来有多少错误是由于错误的缩进而被意外引入的。。。