[Python-ideas] Allow using ** twice

Andrew Barnert abarnert at yahoo.com
Thu Jun 6 20:36:23 CEST 2013


On Thu, Jun 6, 2013 at 1:40 PM, Markus Unterwaditzer <markus at unterwaditzer.net> wrote:

>> Actually i wouldn't expect += to be the same as dict.update, but it rather would create a new dictionary.

Why? The whole point of += is that it does a mutating in-place addition. That's how it works with all other mutable types; why would it work differently with dict?

The reason we don't have this today is that it's not necessarily clear what "addition" means for dicts; it's completely clear what "mutable addition" would mean if we knew what "addition" meant.


From: Haoyi Li <haoyi.sg at gmail.com>
Sent: Thursday, June 6, 2013 10:53 AM
>Yeah, and I didn't expect list_a += list_b to be the same as list_a.extend(list_b) (I've had plenty of bugs from this, too!), but it is. I think dicts should be consistent with lists, even if I'd prefer it if both of them had a += b desugar into a = a + b.


That would make += misleading. In any other language with a += operator, it mutates. (And pure immutable languages don't have a += operator.) That's why we have __iadd__ and friends in the first place.

In fact, I'd almost prefer it if a += b _never_ desugared into a = a + b (that is, if the default implementation of __iadd__ were to raise NotImplemented instead of to call __add__), but I understand why it's useful for, e.g., teaching novices with integer variables.


In general, for mutable objects, += is the primitive operation (extend, update, etc.), and + is conceptually "copy, then += the copy". (But of course it's often more efficient or more readable to implement each of them independently.)


More information about the Python-ideas mailing list