首页 > 解决方案 > 注释不存在的 dict 字段不应该产生错误吗?

问题描述

有人可以解释为什么在注释不存在的dict字段时没有错误吗?

dict_1 = {}
dict_1['a']: 'aa' #used colon by mistake instead of assign, code passes without any error on python3.7.2

print(__annotations__) # prints empty dict {}
dict_1['a'] # as expected KeyError: 'a'

编辑:在测试了更多案例后,我发现注释现有的 dict 字段也不会产生任何结果。

dict_2 = {'a': 'b'}
dict_2['a']: 'c' # no error here so I would expect to get new annotation
print(__annotations__) # produces empty dict {}

标签: pythonpython-3.xpython-3.7

解决方案


您可以注释任何有效的分配目标。参考PEP 536 中的注释表达式

注释的目标可以是任何有效的单一赋值目标,至少在语法上是这样(这取决于类型检查器如何处理):

class Cls:
    pass

c = Cls()
c.x: int = 0  # Annotates c.x with int.
c.y: int      # Annotates c.y with int.

d = {}
d['a']: int = 0  # Annotates d['a'] with int.
d['b']: int      # Annotates d['b'] with int.

请注意,即使是带括号的名称也被视为表达式,而不是简单的名称:

(x): int      # Annotates x with int, (x) treated as expression by compiler.
(y): int = 0  # Same situation here.

带注释的赋值语句的文档将表明未存储这些值。大概是由静态类型检查工具来存储它们。

对于作为赋值目标的表达式,如果在类或模块范围内,则评估注释,但不存储。


推荐阅读