python - 用属性链换行

标签 python pep8 word-wrap

我通常使用括号将长行换行,如 PEP8 中的建议。 :

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

但是对于像这样的长线,我不确定推荐的方式是什么:

my_object = my_toolbox_with_a_pretty_long_name.some_subset_with_a_pretty_long_name_too.here_is_what_i_was_looking_for

重点是,即使是 = 符号之后的部分仍然太长,我不知道在哪里/如何剪切。

1 - 展开为多行

我经常这样做

toolbox = my_toolbox_with_a_pretty_long_name
subset = toolbox.some_subset_with_a_pretty_long_name_too
my_object = subset.here_is_what_i_was_looking_for

但它有点不同,因为它创建中间变量,尽管在功能上它是等效的。另外,如果该行处于多重条件,例如 if a is not None and len(my_toolbox_..._for) == 42,我真的无法做到这一点。

2 - 使用括号

这也有效:

my_object = (
    my_toolbox_with_a_pretty_long_name
   ).some_subset_with_a_pretty_long_name_too.here_is_what_i_was_looking_for

my_object = ((my_toolbox_with_a_pretty_long_name
              ).some_subset_with_a_pretty_long_name_too
             ).here_is_what_i_was_looking_for

但它在可读性方面相当糟糕,并且建议这样做以避免 85 左右的字符行让我看起来像一个 PEP8 纳粹。我什至无法让后者同时满足 pylint 和 flake8 的要求。

最佳答案

您只需要一对括号:

my_object = (my_toolbox_with_a_pretty_long_name
.some_subset_with_a_pretty_long_name_too
.here_is_what_i_was_looking_for)

换行符在括号表达式中并不重要,它们可以出现在允许空格的任何地方。

对于您的另一个示例:

   if (a is not None 
       and len(my_toolbox_with_a_pretty_long_name
               .some_subset_with_a_pretty_long_name_too
               .here_is_what_i_was_looking_for) == 42):

关于python - 用属性链换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44131168/

相关文章:

python - 三元返回/赋值与传统 if-else block 的比较

CSS - 不允许切片

css - 将长帖子标题换行

Python Windows 错误 : [Error 3] The system cannot find the file specified when trying to rename

python - 如何将颜色条以 seaborn 热图的定义值居中?

python - 您将如何正确地打破这一行以匹配 pep8 规则?

c++ - 是否有用于 80 列格式化文本输出的库/方法?

python - 如何从本身从标准输入读取的标准输入运行 Python 源代码?

python - Curl 和 Python Requests (get) 报告不同的 http 状态代码

python - 在 Python 中使用 PEP 8 标准声明类对象(pylint 错误)