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

但这不是很漂亮

你能推荐另一种方法吗?


当前回答

您不需要在第二个条件行上使用4个空格。可能使用:

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

不过这两个都相当难看。

也许会失去括号(尽管《风格指南》不鼓励这样做)?

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

这是《风格指南》,(自2010年以来)建议使用括号。

其他回答

就我个人而言,我喜欢给长if语句增加意义。我必须在代码中搜索以找到合适的示例,但这是我想到的第一个示例:假设我碰巧遇到了一些奇怪的逻辑,我想根据许多变量显示某个页面。

英语:“如果登录的用户不是管理员教师,而是普通教师,而不是学生本人……”

if not user.isAdmin() and user.isTeacher() and not user.isStudent():
    doSomething()

当然,这看起来很好,但阅读那些if语句是一项艰巨的工作。我们把逻辑分配给有意义的标签怎么样。“标签”实际上是变量名:

displayTeacherPanel = not user.isAdmin() and user.isTeacher() and not user.isStudent()
if displayTeacherPanel:
    showTeacherPanel()

这可能看起来很愚蠢,但您可能还有另一种情况,即您只想显示另一个项目,如果您正在显示教师面板,或者用户默认可以访问其他特定面板:

if displayTeacherPanel or user.canSeeSpecialPanel():
    showSpecialPanel()

尝试在不使用变量来存储和标记逻辑的情况下编写上述条件,不仅结果是一个非常混乱、难以理解的逻辑语句,而且你自己也在重复。虽然有合理的例外,但请记住:不要重复自己(干)。

我也一直在努力找到一种体面的方式来做这件事,所以我只是想出了一个主意(不是银弹,因为这主要是品味问题)。

if bool(condition1 and
        condition2 and
        ...
        conditionN):
    foo()
    bar()

与我见过的其他解决方案相比,我发现这个解决方案有一些优点,即,您可以获得额外的4个缩进空间(bool),允许所有条件垂直排列,并且if语句的主体可以以清晰的方式缩进。这也保留了布尔运算符短路求值的优点,但当然增加了基本上什么都不做的函数调用的开销。您可以(有效地)辩称,任何返回其参数的函数都可以在这里使用,而不是bool,但正如我所说,这只是一个想法,最终还是一个口味问题。

有趣的是,当我写这篇文章并思考“问题”时,我想到了另一个想法,它消除了函数调用的开销。为什么不使用额外的括号对来表示我们将要进入一个复杂的条件呢?再多说2个,以相对于if语句的主体对子条件进行2个空格的缩进。例子:

if (((foo and
      bar and
      frob and
      ninja_bear))):
    do_stuff()

我有点喜欢这样,因为当你看着它时,一个铃声立刻在你的脑海中响起:“嘿,这里发生了一件复杂的事情!”。是的,我知道括号对可读性没有帮助,但这些条件应该很少出现,当它们出现时,你必须停下来仔细阅读它们(因为它们很复杂)。

总之,还有两个我没有看到的提案。希望这对某人有所帮助:)

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

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

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

简单明了,也通过了pep8检查:

if (
    cond1 and
    cond2
):
    print("Hello World!")

近年来,我一直倾向于使用所有和任何函数,因为我很少将“与”和“或”进行比较,这很有效,并且具有“早期失败”和生成器理解的额外优势:

if all([
    cond1,
    cond2,
]):
    print("Hello World!")

只需记住传入一个可迭代的!传入N个参数不正确。

注意:任何一个都像许多或比较,所有都像许多和比较。


这很好地结合了生成器的理解,例如:

# Check if every string in a list contains a substring:
my_list = [
    'a substring is like a string', 
    'another substring'
]

if all('substring' in item for item in my_list):
   print("Hello World!")

# or

if all(
    'substring' in item
    for item in my_list
):
    print("Hello World!")

更多内容:生成器理解

我知道这个线程很旧,但我有一些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能咬紧牙关,只带上大括号。我想知道这些年来有多少错误是由于错误的缩进而被意外引入的。。。