[Python-ideas] Augmented assignment [was Re: Adding "+" and "+=" operators to dict]

Andrew Barnert abarnert at yahoo.com
Sun Feb 15 07:19:49 CET 2015


On Feb 14, 2015, at 22:11, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:

> Andrew Barnert wrote:
>> Consider any object with a cache that has to be invalidated when one of its
>> members or attributes is set.
> 
> If obj were such an object, then obj.member.extend(foo)
> would fail to notify it of a change.

Sure. Again, this is why every sorted container, caching object, etc. out there has to document "please don't mutate the keys/elements/members" and hope people read the docs. But you're always allowed to _assign_ to the elements. And, because of the semantics of Python, that includes augmented assignment. And people have used that fact in real code.

> Also, if obj1 and obj2 are sharing the same list, then
> obj1.member += foo would only notify obj1 of the change
> and not obj2.

Sure, and this subtlety does--rarely, but occasionally--come up in real code, and then you have to think about what to do about it.

Does that mean it would be better to face the problem every time, right from the start? In a new language, I might say yes.

> For these reasons, I wonder whether relying on a side
> effect of += to notify an object of changes is a good
> design.

But that's not the only question when you're proposing a breaking change. Even if it's a bad design, is it worth going out of our way to break code that relies on that design?


More information about the Python-ideas mailing list