3 ms·
Why does a = a['k'] = {} create an infinitely nested dictionary?
- xg15 5y agoThis is an interesting example that the internal models of two programming languages can be quite different, even if they ostensibly support the same features. a=a['k']={} is also valid JavaScript, however running it throws an exception and generally works as OP probably expected the statement to work. The reason is that in JS, the statement is parsed as a = (a['k']={}) where (a['k']={}) is executed first and also returns the assigned value. Meanwhile in Python, apparently multi-assignment is a grammar production of its own, so the above would be parsed as sort of: multi-assign(a, a['k']) = {} and therefore first assign to a, then to a['k'].
- deleted 5y ago[deleted]
- oshiar53-0 5y agoYet another reason is all the references in LHS expressions are resolved before the inner expression is executed. Thus a['k'] = a = {} won't still work.
- xg15 5y agoYou mean in JS? Good to know, I wasn't aware of that.
- jwmhjwmh 5y agoIMO it would make more sense to just treat assignments as expressions, as is done in C-like languages. Maybe I'm just more accustomed to C-like languages, though. I think that one thing that makes the statement confusing is that the first equals sign serves a purpose completely different from the second equals sign, but both of them are represented by the same character.