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

问题描述 投票:2回答:1

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

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 {}
python python-3.x python-3.7
1个回答
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,将指示未存储这些值。大概由静态类型检查工具来存储它们。

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

© www.soinside.com 2019 - 2024. All rights reserved.