拆分的长条件表达式线

问题描述:

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

+5

只是一个评论,你没有必要在你的例子中有一个'if'语句。你可以'return(self.expires是None或datetime.now()...)' – mgilson 2012-07-30 14:01:33

+0

我刚刚学习Python,我想我可以做到这一点,但没有那么好。谢谢mgilson – kbec 2012-07-30 14:07:21

在整个条件下添加更多等级的括号。这将允许您根据需要插入换行符。

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

把换行符括号内 if ((....) and (...)):

你可以反转测试并在测试的子集上返回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 

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

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

+0

谢谢,但这真的更可读?一个'if'在逻辑上被打破对我来说更具可读性 - 我可以像许多带有共享结果语句的ifs一样对待它。 – kbec 2012-07-30 14:12:55

+4

是的,绝对。您有两个逻辑上不相关的理由使您的内容无效。要么它已经过期,要么仍然达到0.如果将来还有更多的原因呢?保持这些分离可以提高可读性和可维护性。 – 2012-07-30 14:21:00

+0

如果还有其他原因,您可能是对的。 – kbec 2012-07-30 14:27:37