问题描述
我使用的是 Python 3.6.1,我遇到了一些非常奇怪的事情.我有一个简单的字典分配拼写错误,我花了很长时间才找到.
I am using Python 3.6.1, and I have come across something very strange. I had a simple dictionary assignment typo that took me a long time to find.
context = {}
context["a"]: 2
print(context)
输出
{}
代码 context["a"]: 2
是做什么的?当它应该 IMO 时,它不会引发 SyntaxError
.起初我以为它是在创建一个切片.但是,键入 repr(context["a"]: 2)
会引发 SyntaxError
.我还在控制台中输入了 context["a"]: 2
并且控制台没有打印任何内容.我想也许它返回 None
,但我不太确定.
What is the code context["a"]: 2
doing? It doesn't raise a SyntaxError
when it should IMO. At first I thought it was creating a slice. However, typing repr(context["a"]: 2)
raises a SyntaxError
. I also typed context["a"]: 2
in the console and the console didn't print anything. I thought maybe it returned None
, but I'm not so sure.
我也认为它可以是单行 if 语句,但这也不应该是正确的语法.
I've also thought it could be a single line if statement, but that shouldn't be the right syntax either.
此外,context["a"]
应该引发 KeyError
.
我很困惑.怎么回事?
推荐答案
你不小心写了一个语法正确的变量注释.该功能是在 Python 3.6 中引入的(参见 PEP 526).
You have accidentally written a syntactically correct variable annotation. That feature was introduced in Python 3.6 (see PEP 526).
虽然变量注释被解析为 带注释的赋值的一部分,赋值语句是可选的:
Although a variable annotation is parsed as part of an annotated assignment, the assignment statement is optional:
annotated_assignment_stmt ::= augtarget ":" expression ["=" expression]
因此,在 context["a"]: 2
context["a"]
是注解目标2
是注解本身context["a"]
未初始化
context["a"]
is the annotation target2
is the annotation itselfcontext["a"]
is left uninitialised
PEP 声明注解的目标可以是任何有效的单一赋值目标,至少在语法上是(这取决于类型检查器如何处理)",这意味着不需要对密钥进行注释(因此没有 KeyError
).以下是原始 PEP 的示例:
The PEP states that "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)", which means that the key doesn't need to exist to be annotated (hence no KeyError
). Here's an example from the original PEP:
d = {}
d['a']: int = 0 # Annotates d['a'] with int.
d['b']: int # Annotates d['b'] with int.
通常,注释表达式应该评估为 Python 类型 --毕竟注解的主要用途是类型提示,但并没有强制执行.注释可以是任何有效 Python 表达式,无论结果的类型或值如何.
Normally, the annotation expression should evaluate to a Python type -- after all the main use of annotations is type hinting, but it is not enforced. The annotation can be any valid Python expression, regardless of the type or value of the result.
如您所见,此时类型提示非常宽松且很少有用,除非您有静态类型检查器,例如 mypy.
As you can see, at this time type hints are very permissive and rarely useful, unless you have a static type checker such as mypy.
这篇关于这种奇怪的结肠行为在做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!