Python's documentation on the methods related to the in-place operators like += and *= (or, as it calls them, the augmented arithmetic assignments) has the following to say:
These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods.
I have two closely related questions:
- Why is it necessary to return anything from these methods if the documentation specifies that, if implemented, they should only be doing stuff in-place anyway? Why don't the augmented assignment operators simply not perform the redundant assignment in the case where
__iadd__is implemented? - Under what circumstances would it ever make sense to return something other than
selffrom an augmented assignment method?
A little experimentation reveals that Python's immutable types don't implement __iadd__ (which is consistent with the quoted documentation):
>>> x = 5
>>> x.__iadd__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__iadd__'
and the __iadd__ methods of its mutable types, of course, operate in-place and return self:
>>> list1 = []
>>> list2 = list1
>>> list1 += [1,2,3]
>>> list1 is list2
True
As such, I can't figure out what the ability to return things other than self from __iadd__ is for. It seems like it would be the wrong thing to do in absolutely all circumstances.