Python 3.9及以后版本:dict与typing.Dict该如何选择?
在Python 3.9+中选择dict还是typing.Dict进行类型注解?
在Python 3.9及以后的版本里,直接用内置的dict做类型注解就对了,不用再纠结typing.Dict。
核心原因:
- 3.9开始,Python的内置集合类型(
dict、list、set等)都支持了下标式的类型参数声明,比如dict[str, int]和旧的typing.Dict[str, int]功能完全等价。 typing.Dict已经被官方标记为弃用,虽然目前还能运行,但后续版本大概率会被移除,官方明确推荐用内置类型替代。- 用
dict的代码更简洁,不需要额外导入typing模块里的对应类型,减少不必要的依赖。
示例对比
3.9+的推荐写法:
def update_scores(scores: dict[str, int]) -> dict[str, int]: for name in scores: scores[name] += 10 return scores
3.9以前的兼容写法(现在不推荐):
from typing import Dict def update_scores(scores: Dict[str, int]) -> Dict[str, int]: for name in scores: scores[name] += 10 return scores
特殊情况
如果你的代码需要兼容Python 3.8及更早版本,那还是得保留typing.Dict;但如果只面向3.9+的环境,直接用dict就好。
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

