且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

这种奇怪的结肠行为在做什么?

更新时间:2023-11-20 20:11:10

你不小心写了一个语法正确的变量注释.该功能是在 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 target
  • 2 is the annotation itself
  • context["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.