+= return value

Greg Ewing greg at cosc.canterbury.ac.nz
Tue Jan 23 20:23:02 EST 2001


shochet at hotmail.com wrote:
> 
> I am confused with the return values of the augmented assignment
> opertators. When redefining them in a class, what should they return?

They should return whatever it is you want
to be assigned to the left hand side.

> Why do these operators need any return value? 
> It would seem enough simply to set the object's internal
> state.

That's fine if the object's internal state *can* be set,
i.e. if the object is mutable, but not if it's immutable.

There was a long debate about this when the feature was
being considered. Some people thought that x += y should
just be syntactic sugar for x = x + y, so that it would
work on both mutable and immutable values. Others thought
that it should actually mutate the object on the left hand
side, but then it would only work on mutable objects, and
people who tried to do

> x = 2
> x+=1

would get a nasty surprise.

Eventually the current solution was settled upon, which is
that the return value of the method is assigned to the left
hand side. That way, objects which want to mutate themselves
can do so and return self, whereas objects which are immutable,
or don't want to mutate themselves, can create a new object
and return that. So you get the best of both worlds.

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list