Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is python assignment strictly evaluated right to left? [duplicate]

In other words is

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

safe in Python?

I know this is undefined behaviour in C++; where the program might get a reference to the element before computing the value it's going to assign to it. Is this similar in Python or is len(d) always computed before d.__getitem__("key")?

like image 832
csiz Avatar asked Apr 20 '15 16:04

csiz


2 Answers

Yes, in Python it is safe: the evaluation order of an expression is from left to right, but in an assignment statement the right side is evaluated before the assignment happens. Also an arithmetic expression is evaluated in the arithmetic order of their suffixes.

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:

like image 79
Abhijit Avatar answered Nov 14 '22 22:11

Abhijit


Yes, the RHS of an assignment is evaluated before the LHS; this is the case whether the LHS is an attribute reference, a subscription or a slicing.

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

The succeeding language in the section discusses how assignment to different target syntaxes are defined, but does so from the standpoint that the expression list has already been evaluated to yield an object.

Indeed, the order of evaluation within the LHS is also defined; the container is evaluated before the subscript:

  • 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.
like image 38
ecatmur Avatar answered Nov 14 '22 23:11

ecatmur