【问题标题】:Split long conditional expressions to lines将长条件表达式拆分为行
【发布时间】:2012-07-28 05:03:20
【问题描述】:

我有一些 if 语句,例如:

def is_valid(self):
    if (self.expires is None or datetime.now() < self.expires)
    and (self.remains is None or self.remains > 0):
        return True
    return False

当我输入这个表达式时,我的 Vim 会自动将 and 移动到新行,缩进与 if 行相同。我尝试了更多的缩进组合,但验证总是说那是无效的语法。如何构建long if's?

【问题讨论】:

  • 只是一个评论,没有必要在你的例子中有if 声明。你可以return (self.expires is None or datetime.now() ...)
  • 我刚刚学习 Python,我想我可以做到,但感觉不太好。谢谢 mgilson

标签: python if-statement python-2.6


【解决方案1】:

在整个条件周围添加一层额外的括号。这将允许您根据需要插入换行符。

if (1+1==2
  and 2 < 5 < 7
  and 2 != 3):
    print 'yay'

关于实际使用的空间数量,Python Style Guide 没有任何要求,只是给出了一些想法:

# No extra indentation.
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

【讨论】:

    【解决方案2】:

    将换行符放在括号内 if ((....) and (...)):

    【讨论】:

      【解决方案3】:

      您可以反转测试并在测试的子集上返回 False:

      def is_valid(self):
          if self.expires is not None and datetime.now() >= self.expires:
              return False
          if self.remains is not None and self.remains <= 0:
              return False
          return True
      

      通过这种方式,您可以分解一长串测试,让整个测试变得更具可读性。

      是的,您可以在布尔测试周围使用额外的括号以允许在测试中使用换行符,但是当您必须跨越多行时,可读性会受到很大影响。

      【讨论】:

      • 谢谢,但这真的更具可读性吗?一个 if 在逻辑上被打破对我来说更具可读性 - 我可以像使用共享结果语句的许多 if 一样对待它。
      • 是的,当然。您的内容无效有 2 个逻辑上不相关的原因。要么是过期了,要么是results已经到了0,如果以后还有更多的原因呢?将它们分开可以提高可读性和可维护性。
      • 顺便说一句,请不要尝试像if A: return False / if B: return True / if C: return False / return True 这样的“混合”级联,它们读起来更糟,用括号写起来更好。
      猜你喜欢
      • 1970-01-01
      • 2020-12-31
      • 2021-04-17
      • 2019-02-24
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多