Is the right-hand side of an assignment always evaluated before the assignment?

纵然是瞬间 提交于 2019-11-26 16:57:04

问题


Here is a code snippet.

x = {}
x[1] = len(x)

print x
{1: 0}

Is this well defined? That is, could x == {1: 1} instead?

Because I remember that an equivalent program in C++ '98 (if we use std::map) has undefined behaviour. The output of the program was different when compiled with VS compiler and G++.


回答1:


As I mentioned in a comment, this test case can be reduced to:

x = {}
x[1] = len(x)

The question then becomes, is x[1] == 0, or is x[1] == 1?

Let's look at the relevant 2.x documentation and 3.x documentation:

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:

expr3, expr4 = expr1, expr2

Therefore...

len(x) will be fully computed before we do x[1], so x[1] == 0 and this is well defined.




回答2:


Yes, it's defined. len() is called before the assignment. However, dict's are not ordered in Python, which is why you sometimes see 0, 1 and 1, 0 in the output.



来源:https://stackoverflow.com/questions/27112647/is-the-right-hand-side-of-an-assignment-always-evaluated-before-the-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!