Python 行宽规范 80 字符 | Google 官方换行指南

2025-07-28 14:25 更新

行宽

Tip

最大行宽是 80 个字符。

例外:

  1. 长的导入(import)语句。
  2. 注释里的 URL、路径名以及长的标志(flag)。
  3. 不便于换行、不包含空格、模块级的长字符串常量,比如 URL 或路径名。
  4. Pylint 禁用注释。(例如:# pylint: disable=invalid-name

不要用反斜杠表示 显式续行 (explicit line continuation)。 应该利用 Python 的 圆括号, 中括号和花括号的隐式续行 (implicit line joining) 。如有需要,你可以在表达式外围添加一对括号。

正确:

foo_bar(self, width, height, color='黑', design=None, x='foo',
        emphasis=None, highlight=0)


if (width == 0 and height == 0 and
    color == '红' and emphasis == '加粗'):


(bridge_questions.clarification_on
 .average_airspeed_of.unladen_swallow) = '美国的还是欧洲的?'


with (
    very_long_first_expression_function() as spam,
    very_long_second_expression_function() as beans,
    third_thing() as eggs,
):
    place_order(eggs, beans, spam, beans)

错误:

if width == 0 and height == 0 and \
    color == '红' and emphasis == '加粗':


bridge_questions.clarification_on \
    .average_airspeed_of.unladen_swallow = '美国的还是欧洲的?'


with very_long_first_expression_function() as spam, \
        very_long_second_expression_function() as beans, \
        third_thing() as eggs:
    place_order(eggs, beans, spam, beans)

如果字符串的字面量 (literal) 超过一行,应该用圆括号实现隐式续行:

x = ('这是一个很长很长很长很长很长很长'
     '很长很长很长很长很长的字符串')

最好在最外层的语法结构上分行。如果你需要多次换行,应该在同一层语法结构上换行。

正确:

bridgekeeper.answer(
     name="亚瑟", quest=questlib.find(owner="亚瑟", perilous=True))


 answer = (a_long_line().of_chained_methods()
           .that_eventually_provides().an_answer())


 if (
     config is None
     or 'editor.language' not in config
     or config['editor.language'].use_spaces is False
 ):
   use_tabs()

错误:

bridgekeeper.answer(name="亚瑟", quest=questlib.find(
    owner="亚瑟", perilous=True))


answer = a_long_line().of_chained_methods().that_eventually_provides(
    ).an_answer()


if (config is None or 'editor.language' not in config or config[
    'editor.language'].use_spaces is False):
  use_tabs()

必要时,注释中的长 URL 可以独立成行。

正确:

## 详情参见
## https://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html

错误:

## 详情参见
## https://www.example.com/us/developer/documentation/api/content/\
## v2.0/csv_file_name_extension_full_specification.html

注意上面各个例子中的缩进;详情参见 Black 或 Pyink 自动格式化工具无法继续缩减行宽,则允许该行超过 80 个字符。我们也鼓励作者根据上面的规则手动拆分。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号