python 3.10 相比 3.7 在类型提示上更简洁自然:支持 str | int 替代 union[str, int]、list[int] 等内置泛型替代 typing.list[int],以及 typeddict 默认 total=false;3.7 虽支持完整静态检查,但语法受限且部分新写法会报 syntaxerror。

Python 3.7 和 3.10 在类型提示上的核心区别不是“能不能用”,而是“怎么写更自然、更少依赖 typing 模块”。3.10 的语法更简洁,但 3.7 已具备完整静态检查能力——只要工具链(如 mypy)支持,类型逻辑本身是等价的。
Union 类型写法:从 Union[str, int] 到 str | int
这是最直观的差异。3.7 必须从 typing 导入 Union,而 3.10 原生支持管道符语法:
# Python 3.7
from typing import Union
def parse_id(value: Union[str, int]) -> int:
return int(value)
<h1>Python 3.10+</h1><p>def parse_id(value: str | int) -> int:
return int(value)
</p>
注意:str | int 在 3.10+ 是语法糖,运行时仍被解析为 Union[str, int];但 3.7 直接写 str | int 会报 SyntaxError: invalid syntax。
常见错误现象:
- 在 3.7 项目里误用
str | int,CI 构建直接失败 - 团队混用版本时,有人提交了管道符语法,别人本地跑 mypy 却不报错(因为 mypy 支持该语法早于 Python 解释器),但
ast.parse()或某些 IDE 插件会崩溃
内置集合类型:从 List[int] 到 list[int]
Python 3.9 引入、3.10 全面可用的内置泛型,让 list、dict、tuple、set 可直接带下标使用:
# Python 3.7(必须导入)
from typing import List, Dict, Tuple
config: Dict[str, List[int]] = {"ports": [80, 443]}
<h1>Python 3.10+</h1><p>config: dict[str, list[int]] = {"ports": [80, 443]}
</p>
关键点:
-
list[int]在 3.7 中是非法语法,解释器会抛SyntaxError - 即使你用 mypy 检查 3.7 代码,也不能在类型注解里写
list[int]—— mypy 不负责语法解析,它依赖 Python 自身的 AST 构建 -
typing.List[int]在 3.10 仍可用,但官方已标记为 deprecated(仅警告,不报错)
TypedDict 的默认行为变化
TypedDict 在 3.8 加入 typing,但直到 3.10 才支持“总字段”(total=False)作为默认参数:
# Python 3.10+:可选字段更直观
from typing import TypedDict
<p>class User(TypedDict, total=False):
name: str
age: int</p><p>u: User = {} # 合法:name 和 age 都可选</p><h1>Python 3.7:必须显式传 total=False,且 TypedDict 在 typing 中</h1><p>from typing import TypedDict</p><p>class User(TypedDict, total=False): # 这行在 3.7 能跑,但部分旧版 mypy 不识别
name: str
age: int
</p>
容易踩的坑:
- 3.7 环境下用
total=False但 mypy 版本太老( - 3.10+ 项目若用
typing_extensions回填TypedDict,要注意其total参数行为与标准库是否一致
type 语句:3.12 新增,3.7/3.10 都不支持
虽然标题问的是 3.7 vs 3.10,但常有人混淆——type Vector = list[float] 是 3.12 才有的语法,**3.7 和 3.10 都不支持**。两者都只能用赋值方式模拟:
# 所有版本通用(包括 3.7 和 3.10) from typing import List Vector = List[float] <h1>3.12+ 才能这么写</h1><p>type Vector = list[float] </p>
这点特别容易被文档误导:看到“Python 3.10 支持类型别名”,其实指的是对 Union、Literal 等高级别名的支持增强,而非 type 语句本身。
真正容易被忽略的是兼容性边界:3.10 的新语法(如 |、list[int])一旦写进代码,就锁死了最低 Python 版本;而类型检查逻辑本身(比如嵌套 Dict[str, Optional[List[Union[int, str]]]])在 3.7 上用 mypy 也能跑通——只是写起来更啰嗦、易出错。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











