python - 将长条件表达式拆分为行

标签 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 行相同。我尝试了更多的缩进组合,但验证总是说那是无效的语法。如何构建long if's?

最佳答案

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

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

关于python - 将长条件表达式拆分为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11723018/

相关文章:

ruby-on-rails - 增加购物车数量 RoR

python - 如何让 Popen 写入文件

python - 获取Python中的所有对象属性?

python - 在 matplotlib 中标记 latex 中的刻度

python - 如何在Python中按第一个和最后一个字符拆分字符串

matlab - if 语句之间和/或 if 语句中的层次结构

javascript - 创建一个if语句是否应该使用if语句?

c++ - 使用自定义模块构建 python 解释器时出现问题

python - 如何通知 PyCharm 自定义模块的位置?

python - 如何使用 pandas 创建新的 df 列以使用正则表达式获取列名称和值?