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

前端 未结 2 1862
遥遥无期
遥遥无期 2020-12-01 20:18

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?

2条回答
  •  情歌与酒
    2020-12-01 20:46

    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.

提交回复
热议问题