2 ms·
One related area where Python is not consistent is operators like +=. In pretty much all other languages that have them, the expected behavior of A+=B is exact
by int_19h 5y ago
One related area where Python is not consistent is operators like +=.
In pretty much all other languages that have them, the expected behavior of A+=B is exactly the same as A=A+B, except that A is only evaluated once. Now lets look at lists in Python:
xs = [1, 2]
ys = xs
ys = ys + [3]
print(xs, ys)
This prints [1, 2] [1, 2, 3], because the third line created a new list, and made ys reference that. On the other hand, this:
xs = [1, 2]
ys = xs
ys += [3]
print(xs, ys)
prints [1, 2, 3] [1, 2, 3], because += changes the list itself, and both xs and ys refer to that same list.
(Note that this is not the same as C++, because in the latter, the variables store values directly, while in Python, all variables are references to values.)
The worst part of it is that Python isn't even self-consistent here. If you only define __add__ in your custom class, you can use both + and += with its instances, with the latter behaving normally. But if you define __iadd__, as list does, then you can do whatever you want - and the idiomatic behavior is to modify the instance!
For comparison, C# lets you overload + but not +=, and automatically synthesizes the latter from the former to enforce the correct behavior.
- milliams 5y agoThe rule in Python is that `=` creates a name binding, where as `+=` does not. That's pretty consistent as far as I can tell.
- roelschroeven 5y agoThe inconsistency is that for immutable objects (or more generally, objects that have __add__ but not __iadd__), '+=' does create a name binding. After 'a = 300; b = 50000', a += b is exactly the same as a = a + b In this case, a new object is created with the value of a + b which then gets bound to the name a.
- int_19h 5y agoNope, += also creates a binding! Try this: xs = [1, 2] def foo(): xs += [3] foo() You'll get an exception saying that local variable xs was used before it was assigned - precisely because += created a new local binding for xs inside foo.