【发布时间】:2017-10-23 04:36:05
【问题描述】:
我通常按照PEP8 中的建议使用括号来换行:
包装长行的首选方法是在圆括号、方括号和大括号内使用 Python 隐含的续行。通过将表达式括在括号中,可以将长行分成多行。这些应该优先使用反斜杠来继续行。
但是对于像这样的长线,我不确定推荐的方式是什么:
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-ish 字符行让我看起来像一个 PEP8 纳粹。而且我什至不能让后者同时取悦 pylint 和 flake8。
【问题讨论】: