[Python-ideas] Adding "+" and "+=" operators to dict

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Feb 14 02:19:18 CET 2015


Chris Barker - NOAA Federal wrote:
> But why does it work
> that way? Because it needs to work on immutable objects. If it didn't,
> then you wouldn't need the "assign back to the original name" step.

This doesn't make it wrong for in-place operators to
work on immutable objects. There are two distinct use
cases:

1) You want to update a mutable object in-place.

2) The LHS is a complex expression that you only want
    to write out and evaluate once.

Case (2) applies equally well to mutable and immutable
objects.

There are ways that the tuple problem could be fixed, such
as skipping the assignment if __iadd__ returns the same
object. But that would be a backwards-incompatible change,
since there could be code that relies on the assignment
always happening.

> If it's in-place for a mutable object, it needs to return self. But
> the python standard practice is that methods that mutate objects
> shouldn't return self ( like list.sort() ) for instance.

The reason for that is to catch the mistake of using a
mutating method when you meant to use a non-mutating one.
That doesn't apply to __iadd__, because you don't
usually call it yourself.

-- 
Greg


More information about the Python-ideas mailing list