python - 缩进包裹的、带括号的 if 条件时的样式

标签 python coding-style

假设我有这个功能

def func(arg1):
    if (arg1 > 5
        and arg1 != 10):
        return "something"

对于 if ( 我该怎么办是 4 个字符长,从而使“返回”位看起来很奇怪(并且可能具有误导性)?请不要说把if内容在 1 行,在我的实际代码中,内容超过 79 个字符。

我想到了几个选择:

A)

def func(arg1):
    if (arg1 > 5
        and arg1 != 10
        ):
        return "something"

B)

def func(arg1):
    if (
        arg1 > 5
        and arg1 != 10
    ):
        return "something"

题外话,但是孤儿):看起来像一张不高兴的脸:(

最佳答案

PEP 8 recommends a double-indent in similar cases ,我认为看起来不错:

def func(arg1):
    if (arg1 > 5
            and arg1 != 10):
        return "something"

但是

This PEP explicitly takes no position on how or whether to further visually distinguish continuation lines after multi-line if statements.

因此您实际上可以根据它使用任何可接受的选项:

# No extra indentation.
if (this
    and that):
    do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this
    and that):
    # Since both conditions are true, we can frobnicate.
    do_something()


# Add some extra indentation on the conditional continuation line.
if (this
        and that):
    do_something()

关于python - 缩进包裹的、带括号的 if 条件时的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23982616/

相关文章:

python - 避免数据帧中的重复数据连接/合并/连接

coding-style - 有作者姓名的代码是绝对必要的吗?

math - 在 switch case 语句中检测 2 个变量值的 4 个排列

ruby-on-rails - 如何防止过多的 if-else 条件

python - Pymysql插入不起作用

python - 在 Docker 上使用需求文件构建 pipelinev

Python Hive 客户端 pyhs2 : How to return results from a select statement?

Python:JSON字符串到字典列表 - 迭代时出错

与库交互时的代码风格 (C)

coding-style - 函数名称中的单数或复数动词?