注释不存在的 dict 字段不应该产生错误吗?
Shouldn't annotating nonexisting dict field produce error?
谁能解释一下为什么在注释不存在的字典字段时没有错误?
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_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.
谁能解释一下为什么在注释不存在的字典字段时没有错误?
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_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.