Python 一行不超过 80 个字符是什么意思?

What does it means to not exceeding 80 characters in a line in Python?

有人提到 Python 脚本中的一行最好不要超过 80 个字符。例如:

print("A very long strings")

是否包括print函数的字符、字符串(包括空格)、括号等?

而且不限于print以外的其他功能吗?

这背后的原因是什么?已经用谷歌搜索了答案,但仍然无法真正得到图片。

是的,它包括任何占用 space 且不限于任何功能的东西

通常,shell 在移动到下一行之前只能在一行中显示 80 个字符。如果您在 CLI 中格式化内容,打印语句中超过 80 个字符将抵消所有格式化。这是因为它们遵循 PEP8 标准。

根据PEP8 standard

Limiting the required editor window width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.

在按 python 编码时遵循 PEP8 约定是个好主意。

长度是多少?

一切都计入宽度。

“标准”

PEP8 是建议 不是 法律。 它很好地解释了原因:

  • 在编辑器中打开多个文件side-by-side
  • 代码审查工具

另外,最多 99 个字符被明确“允许”。

Maximum Line Length

Limit all lines to a maximum of 79 characters.

For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.

Limiting the required editor window width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.

The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all.

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the nominal line length from 80 to 100 characters (effectively increasing the maximum length to 99 characters), provided that comments and docstrings are still wrapped at 72 characters.

实用技巧

除了用 / 续行外,只要涉及到括号,您总是可以使用多行。事实上,它被认为更像pythonic。

例如,您可以re-write这样:

def func(very_long_name_1, very_long_name_2, very_long_name_3, very_long_name_4):
    pass

进入这个:

def func(very_long_name_1, very_long_name_2, 
         very_long_name_3, very_long_name_4):
    pass

或者这个:

def func(very_long_name_1, 
         very_long_name_2, 
         very_long_name_3, 
         very_long_name_4):
    pass

这同样适用于函数调用。

此外,列表(或元组或字典)可以在多行上定义:

my_list = ['string_1',
           'string_2',
           'string_3']

应用正确,这种编码风格提高了可读性。

包括所有内容就行了

原因是太长的行会影响清晰度和可读性。

要使用 python 代码风格 guide 中的示例,哪种更容易阅读?

with open('/path/to/some/file/you/want/to/read') as file_1, open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
         file_2.write(file_1.read())

另一个原因是历史原因。 I link 上面同一部分中的样式指南针对各种情况提到了 72、79 和 80-100 个字符的限制。这些是 punch card.

的列长度