【问题标题】:Python Order Of AssignmentPython Order Of Assignment
【发布时间】:2021-10-08 09:47:10
【问题描述】:

Python assignment order behaves differently than I expected. In javascript I could write this:

x = {};
a = x;

a = a['y'] = {};

console.log(a);
// {}

console.log(x)
// {'y':{}}

Because assignment happens right to left, in a = a['y'] = {};, a['y'] gets assigned {}, then a gets assigned a['y']- which is {};

However, in python this is not the case. The same setup:

x = {}
a = x

a = a["y"] = {}

print(a)
# {"y": {...}}

print(x)
# {}

In python, this makes a a self-referencing object, and doesn't set "y" on x at all. The assignment can't be left to right, because assigning a = a["y"] before "y" is set would throw an error. So what is python doing here and why?

【问题讨论】:

标签: python


【解决方案1】:

Python's assignment "operator" = is a dedicated statement, not an expression; your code is not a composition of two assignment expressions like it is in JavaScript, but one single statement that allows for the possibility of multiple targets. When used with multiple targets, Python:

  1. Stores to targets from left to right
  2. Duplicates the same reference to each target

    So this means:

    a = a["y"] = {}
    

    is equivalent to:

    __unnamed_tmp = {}
    a = __unnamed_tmp
    a["y"] = __unnamed_tmp
    

    in that order, causing the behavior you observe.

【讨论】:

  • That's really good - much clearer explanation than the linked question.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 2022-08-10
  • 1970-01-01
  • 2021-03-02
  • 2022-12-01
相关资源
最近更新 更多