在类型提示中使用冒号“:”

Mag*_*rrr 12 python slice python-3.x python-typing

当对 dict 类型的变量进行类型注释时,通常您会像这样注释它:

numeralToInteger: dict[str, int] = {...}
Run Code Online (Sandbox Code Playgroud)

不过我用冒号而不是逗号重写了它:

numeralToInteger: dict[str : int] = {...}
Run Code Online (Sandbox Code Playgroud)

这也有效,不会引发 SyntaxError 或 NameError。

检查__annotations__全局变量后:

colon: dict[str : int] = {...}
comma: dict[str, int] = {...}

print(__annotations__)
Run Code Online (Sandbox Code Playgroud)

输出是:

{'colon': dict[slice(<class 'str'>, <class 'int'>, None)],
 'comma': dict[str, int]}
Run Code Online (Sandbox Code Playgroud)

因此,冒号被视为切片对象,逗号被视为普通类型提示。

我应该对 dict 类型使用冒号还是应该坚持使用逗号?

我使用的是 Python 版本 3.10.1。

Sor*_*ary 9

如果你有一个字典,其键是字符串,值是整数,那么你应该这样做dict[str, int]。这不是可选的。IDE 和类型检查器使用这些类型提示来帮助您。当你说 时dict[str : int],它是一个切片对象。完全不同的事情。

在mypy Playground中尝试这些:

d: dict[str, int]
d = {'hi': 20}

c: dict[str: int]
c = {'hi': 20}
Run Code Online (Sandbox Code Playgroud)

信息:

main.py:4: error: "dict" expects 2 type arguments, but 1 given
main.py:4: error: Invalid type comment or annotation
main.py:4: note: did you mean to use ',' instead of ':' ?
Found 2 errors in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)

错误消息说明了一切