Python 赋值运算符优先级 - (a, b) = a[b] = {}, 5

Python Assignment Operator Precedence - (a, b) = a[b] = {}, 5

我在 Twitter 上看到了这个 Python 片段并且对输出感到很困惑:

>>> a, b = a[b] = {}, 5
>>> a
{5: ({...}, 5)}

这是怎么回事?

来自Assignment statements documentation:

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

您有两个作业目标列表; a, ba[b],值 {}, 5 从左到右分配给这两个目标。

首先 {}, 5 元组被解包为 a, b。您现在有 a = {}b = 5。请注意 {} 是可变的。

接下来,您将相同的字典和整数分配给 a[b],其中 a 计算为字典,b 计算为 5,因此您正在设置字典中的键 5 到元组 ({}, 5) 创建循环引用。 {...} 因此指的是 a 已经引用的同一个对象。

因为赋值是从左到右进行的,您可以将其分解为:

a, b = {}, 5
a[b] = a, b

所以 a[b][0]a 是同一个对象:

>>> a, b = {}, 5
>>> a[b] = a, b
>>> a
{5: ({...}, 5)}
>>> a[b][0] is a
True