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

£可爱£侵袭症+ 提交于 2019-12-21 05:27:14

问题


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


回答1:


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:




回答2:


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.


来源:https://stackoverflow.com/questions/29753335/is-python-assignment-strictly-evaluated-right-to-left

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