Python import 语句格式规范 | Google 官方分组排序法
2025-07-30 18:08 更新
导入 (import) 语句的格式
Tip
导入语句应该各自独占一行。typing 和 collections.abc 的导入除外。例如:
正确:
from collections.abc import Mapping, Sequence
import os
import sys
from typing import Any, NewType
错误:
import os, sys
导入语句必须在文件顶部,位于模块的注释和文档字符串之后、全局变量和全局常量之前。导入语句应该按照如下顺序分组,从通用到特殊:
-
导入 Python 的
__future__
。例如:from __future__ import annotations
参见前文有关
__future__
语句的描述。 -
导入 Python 的标准库。例如:
import sys
-
导入 第三方 模块和包。例如:
import tensorflow as tf
-
导入代码仓库中的子包。例如:
from otherproject.ai import mind
-
已废弃的规则:导入应用专属的、与该文件属于同一个子包的模块。例如:
from myproject.backend.hgwells import time_machine
你可能会在较老的谷歌风格 Python 代码中遇到这样的模式,但现在不再执行这条规则。我们建议新代码忽略这条规则。同等对待应用专属的子包和其他子包即可。
在每个分组内部,应该按照模块完整包路径(例如 from path import ...
中的 path
)的字典序排序,忽略大小写。可以选择在分组之间插入空行。
import collections
import queue
import sys
from absl import app
from absl import flags
import bs4
import cryptography
import tensorflow as tf
from book.genres import scifi
from myproject.backend import huxley
from myproject.backend.hgwells import time_machine
from myproject.backend.state_machine import main_loop
from otherproject.ai import body
from otherproject.ai import mind
from otherproject.ai import soul
## 旧的代码可能会把这些导入语句放在下面这里:
#from myproject.backend.hgwells import time_machine
#from myproject.backend.state_machine import main_loop
以上内容是否对您有帮助:
更多建议: