python - 注释不存在的 dict 字段不应该产生错误吗?
问题描述
有人可以解释为什么在注释不存在的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 {}
解决方案
您可以注释任何有效的分配目标。参考PEP 536 中的注释表达式:
注释的目标可以是任何有效的单一赋值目标,至少在语法上是这样(这取决于类型检查器如何处理):
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.
带注释的赋值语句的文档将表明未存储这些值。大概是由静态类型检查工具来存储它们。
对于作为赋值目标的表达式,如果在类或模块范围内,则评估注释,但不存储。
推荐阅读
- ios - iOS 14 上的 GoogleCast 框架崩溃
- java - 为什么Java将方法参数视为其局部变量?
- swift - Swift 通用函数不接受输入
- javascript - PHP没有访问Javascript cookie
- macos - 使用 NSAccessibility API/XCUITest 框架的 MacOS 上的 Firefox 自动化是否可行?
- python - ValueError:重复可能不包含负值
- javascript - 重复反应组件的最佳实践
- r - R 从下一个不相等的值中进行条件减法
- hibernate - 批量更新并返回 JPA/Hibernate 中失败更新的 Id
- swift - 在swiftui,ios14中触摸本地通知时重定向到工作表或演示文稿