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

标签 python python-3.x python-3.7

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

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/

相关文章:

python - 激活阿拉伯语翻译后,Django 表单占位符和标签未翻译

python-3.x - 如何将表情符号嵌入到 Tweepy 状态文本中?

pycharm - 是否可以将 PyCharm 中的 Qt Designer 与所有最新版本一起使用?

python-requests - wrap_socket() 得到一个意外的关键字参数 '_context' 和 deserialize(error)

boolean-logic - bool 检查 datetime.now() 是否位于元组列表中任何元组的值之间

python - 在 Python 3 中格式化数字显示

python - 如何将 Python bool 对象转换为 C int(或 C++ bool 值)(Python C API)

python - Healpy:从数据到 Healpix map

python - 如何从可迭代的保持原始索引中枚举选定的元素?

python - 为什么 Python 3 中的 `input` 抛出 NameError : name. .. 未定义