有人能解释一下为什么在注释不存在的字典字段时没有错误吗?
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 {}
最佳答案
您可以注释任何有效的分配目标。引用Annotating Expressions来自 PEP 536:
The target of the annotation can be any valid single assignment target, at least syntactically (it is up to the type checker what to do with this):
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.
Note that even a parenthesized name is considered an expression, not a simple name:
(x): int # Annotates x with int, (x) treated as expression by compiler. (y): int = 0 # Same situation here.
documentation for annotated assignment statements ,将表明这些值没有被存储。大概由静态类型检查工具来存储它们。
For expressions as assignment targets, the annotations are evaluated if in class or module scope, but not stored.
关于python - 注释不存在的 dict 字段不应该产生错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748309/