You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 14:37:05