pep8 符合长 json 字典查找?

pep8 compliance with long json dictionary lookup?

使用79个字符长度,有人会如何制定这样的命令:

return method_returning_json()['LongFieldGroup1']['FieldGroup2']['FieldGroup3']['LongValue']

如果我将查找移动到下一行,例如:

return method_returning_json()\
    ['FieldGroup1']['FieldGroup2']['FieldGroup3']['Value']

pep8 抱怨 "space before [" 因为有几个选项卡。但是,如果我将 second/third/etc 组移动到换行符,它会做同样的事情。

我知道我可以将 # noqa 标记添加到行尾,但我希望有更好的方法。

引用 PEP8:

A Foolish Consistency is the Hobgoblin of Little Minds

One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, "Readability counts".

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!

In particular: do not break backwards compatibility just to comply with this PEP!

Some other good reasons to ignore a particular guideline:

When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.

To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).

Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.

When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.

在我看来(这只是一个意见)有些时候像你这样打破行会使代码更难阅读,所以现在可能是忽略行长准则的合理时间。

话说回来,如果你真的想把行的长度保持在 79 以下,一个 方法可能是将命令实际拆分为单独的行:

some_json = method_returning_json()
key1 = 'FieldGroup1'
key2 = 'FieldGroup2'
key3 = 'FieldGroup3'
return some_json[key1][key2][key3]['Value']

这不像单行方法那么简洁,但每一行都更短。孰轻孰重,由你评判。

使用出现在括号内的隐式续行:

return (method_returning_json()
          ['LongFieldGroup1']
          ['FieldGroup2']
          ['FieldGroup3']
          ['LongValue'])

(您可能需要调整实际缩进以使 pep8 工具满意。)

您甚至可以使用索引括号本身来允许隐式行继续,尽管我并没有发现任何特别可读的变体。

# Legal, but probably not desirable.
# At the very least, pick one style and be consistent; don't
# use a variety of options like I show here.
return method_returning_json()[
         'LongFieldGroup1'][
         'FieldGroup2'][
         'FieldGroup3'
         ][
         'LongValue'
         ]