【问题标题】:Wrapping line with attribute chaining使用属性链包装线
【发布时间】: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。

【问题讨论】:

    标签: python pep8 word-wrap


    【解决方案1】:

    你只需要一对括号:

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

    【讨论】:

    • 哇,太好了,谢谢。我不知道我可以这样写。然后我猜选项 2 这样写是最好的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-06-24
    • 2017-10-20
    • 2017-12-04
    • 1970-01-01
    • 2012-02-16
    • 2015-12-05
    • 1970-01-01
    • 2019-11-03
    相关资源
    最近更新 更多