Python 的 PEP8 行长度限制是否适用于评论?

Does Python's PEP8 line length limit apply to comments?

我正在开展协作 Python 项目。由于 PEP8,我的 IDE (PyCharm) 标记 'minor issues' 代码行超过 120 个字符。然而,只有当我有一个大的注释来解释一些复杂的代码时才会发生这种情况——代码本身永远不会超过限制。我应该将这些长评论变成多行评论以遵守指南还是保持原样?

是的,指南适用于源代码中的 所有 行,包括注释。那是因为它们有助于设定对编辑器宽度的期望。如果行长度建议不适用于评论,您仍然需要滚动编辑器 window 才能阅读评论。

PEP8还是一个指南,不是严格的法则,可以随意忽略。然而,我建议在任何与更广泛的人合作的地方坚持使用它,即使你们都有更宽的屏幕。例如,就个人而言,我喜欢能够并排放置多个编辑器选项卡。

在 Facebook,我们使用 flake8-bugbearsoft-强制行长度,容差为 10%:

B950: Line too long. This is a pragmatic equivalent of pycodestyle’s E501: it considers “max-line-length” but only triggers when the value has been exceeded by more than 10%. You will no longer be forced to reformat code due to the closing parenthesis being one character too far to satisfy the linter. At the same time, if you do significantly violate the line length, you will receive a message that states what the actual limit is. This is inspired by Raymond Hettinger’s “Beyond PEP 8” talk and highway patrol not stopping you if you drive < 5mph too fast. Disable E501 to avoid duplicate warnings.

免责声明:我为 flake8-bugbear 做出贡献。