21

我有一些 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到新行,缩进与ifline 相同。我尝试了更多的缩进组合,但验证总是说那是无效的语法。如何建立long if's?

4

3 回答 3

40

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

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()
于 2012-07-30T13:57:28.833 回答
3

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

于 2012-07-30T13:57:58.330 回答
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

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

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

于 2012-07-30T14:04:20.467 回答