1

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?

micah
  • 7,596
  • 10
  • 49
  • 90

1 Answers1

5

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Also see the [docs](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), which back this up and give the full, general semantics. – user2357112 Nov 20 '22 at 02:05