【问题标题】:Python style with long predicates to if [closed]带有长谓词的 Python 风格 if [关闭]
【发布时间】:2026-02-01 18:20:05
【问题描述】:

考虑这段代码:

if (something1 is not None and
    check_property(something_else) and
    dr_jekyll is mr_hyde):
    do_something(*args)
    other_statements()

尽管代码是以 PEP-8 方式编写的,但显然很难分辨谓词在哪里结束,而正文的语句从哪里开始。

我们设计了两种变体:

if ((something1 is not None) and
    (check_property(something_else)) and
    (dr_jekyll is mr_hyde)):
    do_something(*args)
    other_statements()

这是丑陋的,

if (something1 is not None and
        check_property(something_else) and
        dr_jekyll is mr_hyde):
    do_something(*args)
    other_statements()

这也很丑。

我个人更喜欢#1,我的同事使用#2。是否有一个不丑且符合 PEP-8 的规范解决方案,可以比上面列出的方法提高可读性?

【问题讨论】:

  • 这个问题主要是基于意见的,因此与 SO 无关。
  • 我认为可读性非常接近可量化。
  • 我想我错误地标记了这个。亚历山大的回答似乎很合理,甚至认为这个问题仍然更多是基于意见的。

标签: python coding-style formatting styles pep8


【解决方案1】:

更改 if 语句,使用 all():

if all([something1 is not None, 
        check_property(something_else), 
        dr_jekyll is mr_hyde]):
    #do stuff...

【讨论】:

  • 这更像是 Pythonic
  • 这不等于拥有«raw» if 声明,例如。 G。 if name is not None and len(name) > 5等非常常见的条件,无法转换。
  • all([1 is not None, len(range(3))>1]) -> True
  • name = None 然后all([name is not None, len(name) > 5])?
  • 请注意,如果something1 None,则不会调用check_property()。但是,您的表达式在返回TrueFalse 之前调用check_property()(所有表达式都被计算)。这是一个重要的区别; andor 短路,让您使用它们来防范异常。
【解决方案2】:

根据您的上下文,您可能不需要is not None

>>> a = [1]
>>> if a:
        print "hello, world"


hello, world
>>> if a is not None:
        print "hello, world"


hello, world
>>> 

【讨论】: