User-defined augmented assignment
Tom Anderson
twic at urchin.earth.li
Sat Oct 1 19:58:05 EDT 2005
On Thu, 29 Sep 2005, Pierre Barbier de Reuille wrote:
> a discussion began on python-dev about this. It began by a bug report,
> but is shifted and it now belongs to this discussion group.
>
> The problem I find with augmented assignment is it's too complex, it's
> badly explained, it's error-prone. And most of all, I don't see any
> use-case for it !
>
> The most common error is to consider that :
>
> a += b <==> a.__iadd__(b)
>
> when the truth is :
>
> a += b <==> a = a.__iadd__(b)
>
> which can be very confusing, as the two "a" are not necessarily the
> same.
Indeed. I certainly didn't realise that was how it worked.
> So, what I would suggest is to drop the user-defined augmented
> assignment and to ensure this equivalence :
>
> a X= b <=> a = a X b
>
> with 'X' begin one of the operators.
That seems quite an odd move. Your proposal would lead to even more
surprising behaviour; consider this:
a = [1, 2, 3]
b = a
a += [4, 5, 6]
print b
At present, this prints [1, 2, 3, 4, 5, 6]; if we were to follow your
suggestion, it would be [1, 2, 3].
So, -1, i'm afraid.
I think the right solution here is staring us in the face: if everyone
seems to think that:
a += b <==> a.__iadd__(b)
Then why not make it so that:
a += b <==> a.__iadd__(b)
Principle of Least Surprise and all that.
Since not everything that should support += is mutable (integers, for
example), how about saying that if the recipient of a += doesn't have an
__iadd__ method, execution falls back to:
a = a + b
I say 'a + b', because that means we invoke __add__ and __radd__
appropriately; indeed, the __add__ vs __radd__ thing is a precedent for
this sort of fallback.
Doesn't that leave everyone happy?
tom
--
I'm not quite sure how that works but I like it ...
More information about the Python-list
mailing list