Python Source Code Beautifier
Duncan Booth
duncan.booth at invalid.invalid
Wed Feb 28 11:33:45 EST 2007
Alan Franzoni <alan.franzoni_invalid at geemail.invalid> wrote:
> Yeah, that's right, it could have semantic differences, but that
> shouldn't be the case anyway. I mean, if I don't define an __iadd__
> method, writing
>
> a += n
>
> or
>
> a = a + n
>
> is just the same, right?
>
>
> So, if I bother to define an __iadd__ method, I should make sure it
> works just the same, or I would introduce a very strange and
> hard-to-understand behaviour.
>
If a is mutable and has an appropriate __iadd__ method which mutates it
then the first of those will mutate the original object and the second
will create a new object. That might not matter much if 'a' is the only
name referring to the object, but if there are any other ways to access
it then it will matter.
Compare:
>>> lst = [1, 2, 3]
>>> n = ['oops']
>>> a = lst
>>> a = a + n
>>> a
[1, 2, 3, 'oops']
>>> lst
[1, 2, 3]
>>> lst = [1, 2, 3]
>>> n = ['oops']
>>> a = lst
>>> a += n
>>> a
[1, 2, 3, 'oops']
>>> lst
[1, 2, 3, 'oops']
More information about the Python-list
mailing list