注释不存在的dict字段不应该产生错误吗?

时间:2019-11-07 11:57:56

标签: python python-3.x python-3.7

有人可以解释为什么注释不存在的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 {}

1 个答案:

答案 0 :(得分:2)

您可以注释任何有效的分配目标。来自PEP 536的参考文献Annotating Expressions

  

注释的目标可以是任何有效的单个分配   至少在语法上定位(取决于类型检查器该做什么)   这样做):

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.

documentation for annotated assignment statements,将指示未存储这些值。大概由静态类型检查工具来存储它们。

  

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