python 赋值是从右到左严格计算的吗?

Is python assignment strictly evaluated right to left?

也就是说

d = {}
d["key"] = len(d)

在 Python 安全吗?

我知道这是undefined behaviour in C++;在计算要分配给它的值之前,程序可能会在其中获取对元素的引用。这在 Python 中是相似的还是 len(d) 总是在 d.__getitem__("key") 之前计算?

是的,在Python中是安全的:表达式的求值顺序是从左到右,但在赋值语句 右侧在赋值发生之前被求值。算术表达式也是按照其后缀的算术顺序求值的。

5.14. Evaluation order

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

是的,作业的 RHS 在 LHS 之前评估;无论 LHS 是属性引用、订阅还是切片,都是这种情况。

来自https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

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.

本节中的后续语言讨论了如何定义对不同目标语法的赋值,但是从表达式列表已经被评估以产生对象的角度出发。

确实,LHS 中的求值顺序也有定义;容器在下标之前计算:

  • If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.