Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

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

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++.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...