[Python-ideas] Unpacking iterables for augmented assignment
Jonathan Fine
jfine2358 at gmail.com
Sun Aug 26 14:50:49 EDT 2018
Hi James and Steve
Myself and Steve wrote:
>> Notice that '+=' creates uses the same object when the object is a
>> list, but creates a new object. This raises the question: Why and how
>> does Python behave in this way?
> Lists are mutable and can be modified in place. Tuples are immutable and
> cannot be.
This correctly answers why this happens.
Steve: I wanted James to think about this question. He learns more
that way. (I already knew the answer.)
James: Combining tuple assignment with increment assignment in a
single statement will increase the cognitive burden on both writer and
reader of the line of code.
In other words, in most cases
> a += <EXP1>
> b += <EXP2>
is easy to write and read than
> a, b += <EXP1>, <EXP2>
Now look at:
> a, b += my_object.some_method(args)
It is simpler than:
> value = my_object.some_method(args)
> a += value[0]
> b += value[1]
You can say that here the extra lines increase the cognitive burden.
And I think I'd agree with you.
But I think there's a code-smell here. Better, I think, is to
introduce a type that supports augmented assignment. For example
> vec = Vector(a, b)
> inc = Vector(c, d)
> vec += inc
I hope this helps
--
Jonathan
More information about the Python-ideas
mailing list