将长条件表达式拆分为行

时间:2012-07-30 13:55:38

标签: python if-statement python-2.6

我有一些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行相同的缩进。我尝试更多缩进组合,但验证总是说这是无效的语法。如何建立多长的?

3 个答案:

答案 0 :(得分:24)

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

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()

答案 1 :(得分:3)

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

答案 2 :(得分: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

通过这种方式,您可以打破长长的测试线,让整个事情更具可读性。

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