4 ms·
Usually this op chain feature is used to allow `if a == b == c:`. This is resolved as (a==b) and (a==c). Following this logic the assignment statement is extend
by Loranubi 5y ago
Usually this op chain feature is used to allow `if a == b == c:`. This is resolved as (a==b) and (a==c). Following this logic the assignment statement is extended the same way as far as I understand. It's just more surprising.
- masak 5y agoThe two behaviors don't seem very related. In `if a == b == c`, the value of `b` is evaluated only once, even if `b` is in fact a bigger/side-effecting expression, and `c` might not be evaluated at all. In `a = b = c`, the `c` is evaluated first, and then `a` and `b` are assigned to, left-to-right.
- saghm 5y ago`==` doesn't have side effects though, so you don't have to worry about the order of uses of a variable that appears twice; it will have the same value both Tony's l times. It seems like a bad idea to me to have operators with side effects use the same rules as ones that don't just because they happen to have similar syntactic representations, but I've never written a non-toy programming language, so I guess there could be something I'm missing.
- lilyball 5y agoI don't think so. The assignment behavior here is explicit, not some emergent fact of operator chaining in general. I think it's meant to allow you to say a = b = expr and have both a and b end up with the value of expr. And by defining it in the fashion that it does, it only requires the target list expressions to be evaluated once as an lvalue (or whatever python's equivalent is).
- lilyball 5y agoThinking about it some more, the surprising behavior here is pretty much just that it does the assignments in left-to-right order instead of right-to-left order. If you try and break down `a = b = expr` into a series of binary assignment operators, the natural answer is `a = (b = expr)` (b doesn't exist yet so you can't write `(a = b) = expr`) where `(b = expr)` behaves as though it returns the value again. And I believe this is in fact how it works in Ruby (as Ruby assignments return the value). But Python assignments don't actually return the value, as they are statements and not expressions. Presumably Python does the assignments in left-to-right order because any observable side-effects in the evaluations of a and b would be expected to be in left-to-right order. It just results in counterintuitive behavior like this.