Tricky order of evaluation in multiple assignment

ぐ巨炮叔叔 提交于 2020-01-17 05:40:09

问题


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?


回答1:


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.




回答2:


The python docs gives the answer :

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.



来源:https://stackoverflow.com/questions/33835607/tricky-order-of-evaluation-in-multiple-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!