dict 的类型提示给出 TypeError: 'type' object is not subscriptable

Rob*_* Li 9 python python-3.x python-typing

memo: dict[int, int] = {0: 0, 1: 1} # *our base cases*
Run Code Online (Sandbox Code Playgroud)

返回以下错误:

memo: dict[int, int] = {0: 0, 1: 1} # *our base cases*
Run Code Online (Sandbox Code Playgroud)

Dav*_*izu 17

我想你应该使用Dict,例如:

from typing import Dict

memo: Dict[int, int] = {0: 0, 1: 1}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您使用的dict是哪种类型type

>>> type(dict)
<class 'type'>
>>> type(Dict)
<class 'typing._GenericAlias'>
Run Code Online (Sandbox Code Playgroud)

  • 从 Python 3.9 开始,您可以在注释中使用内置类型。来自打字模块:当相应的预先存在的类得到增强以支持 [] 时,这些类型在 Python 3.9 中变得多余 (8认同)
  • 字典和字典有什么区别? (2认同)