Search code examples
pythonvariablesoperator-precedence

Tricky order of evaluation in multiple assignment


I know the basic rule regarding the multiple assignment in Python:

  • all expressions at the right part of the assignment are evaluated first
  • then evaluated values are bound to variables at the left part

But actually I encountered something quite different and a little more complicated; I would like to know if I may rely on it. While debugging an algorithm, I suddenly discovered that a bug was related to the line:

k[s], k[p] = k[p], None

Because my algorithm found a case where s and p were equal. And obviously in that case, the final value is k[s]=k[p]=None.

In that very specific case, I would rather like the result of:

k[p], k[s] = None, k[p]

which behaves as I want in all cases, even when p == s. In that case, obviously, k[p] initially takes the value None and then the value k[p] back.

Of course I am aware that it could be a good idea to make one test more in order to have a more readable code, but I am very curious to know about the policy of the language in that lesser-known case: what happens when the same variable is affected twice in a multiple assignment?


Solution

  • Yes, you should be able to rely on this.

    From the reference documentation

    If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

    (emphasis mine)

    k[s], k[s] = k[s], None
    

    is equivalent to

    t = k[s]
    k[s] = t
    k[s] = None
    

    Side note: The evaluation order also holds when the right side is a dynamic iterable, e.g. a generator. All necessary elements will be extracted first and assigned left to right.