6

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")?

Community
  • 1
  • 1
csiz
  • 4,742
  • 9
  • 33
  • 46
  • If you mean is there a chance you will see 1 as the value then no. It is also well documented – Padraic Cunningham Apr 20 '15 at 16:30
  • Yes, this is safe in python – sage88 Apr 20 '15 at 16:31
  • 1
    Note that your question is not phrased in a way that means what you intend, if your audience is Python programmers. In Python, you can do `a, b, c = f(x), f(y), f(z)` and evaluation of `f(x)` happens *before* evaluation of `f(z)`. (This is relevant if the function has side-effects.) So evaluation *of the right-hand side* is **left-to-right**. But the RHS is always evaluated before binding anything to the LHS. – John Y Apr 20 '15 at 17:05

2 Answers2

9

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:

Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
Abhijit
  • 62,056
  • 18
  • 131
  • 204
1

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.
ecatmur
  • 152,476
  • 27
  • 293
  • 366