Re:Copying data is wasteful, mutating data is dangerous
by masklinn on Thursday January 09, 2020 @03:08PM
(#22005078)
As an optimisation, you can override += separately from +. A pretty well known oddity related to this is:
Though to be fair, technically nothing prevents "+" from mutating either operator (it'd just get you tarred and feathered).
[ Parent
| on HN ]
Re:Copying data is wasteful, mutating data is dangerous
by Sohcahtoa82 on Thursday January 09, 2020 @03:54PM
(#22005619)
Wait...did it throw an exception, yet still add the item to the list?
EDIT: Tried it myself. Sure enough, it throws the exception, but still adds the item. This seems like a bug.
EDIT Part 2: I understand now. `a[0] += [1]` is internally translated to `a[0] = a[0].__iadd__([1])`. The right-hand side is interpreted, mutating a[0] in-place as expected. But then the re-assignment happens, which throws the exception since you're trying to re-assign a value in a tuple, which is immutable.