将长条件表达式拆分为行

kbe*_*bec 17 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
Run Code Online (Sandbox Code Playgroud)

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

Kos*_*Kos 28

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

if (1+1==2
  and 2 < 5 < 7
  and 2 != 3):
    print 'yay'
Run Code Online (Sandbox Code Playgroud)

关于实际使用的空格数,Python样式指南并没有强制要求,只提出了一些想法:

# 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()
Run Code Online (Sandbox Code Playgroud)