我通常使用括号将长行换行,如 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/