adding in-place operator to Python

Terry Reedy tjreedy at
Tue Sep 23 20:06:57 CEST 2008

Arash Arfaee wrote:
> Hi All,
> Is there anyway to add new in-place operator to Python? Or is there any 
> way to redefine internal in-place operators?

Python does not have 'in-place operators'.  It has 'augmented assignment 
statements' that combines a binary operation with an assignment.  *If* 
the target being rebound is mutable, *then* (and only then) the 
operation can be and is recommended to be done 'in-place'.  User-defined 
mutable classes (as most are) can implement in-place behavior with 
__ixxx__ methods.  But for the reason given below, __ixxx__ methods 
should supplement and not replace direct mutation methods.

Correct terminology is important for understanding what augmented 
assigments do and what they are basically about.

First, most augmented assignments target immutables, in particular, 
numbers and strings, which do not have __ixxx__ methods.  So the 
operation is *not* done in-place.  The only difference from separately 
indicating the assignment and operation is that the programmer writes 
the target expression just once and the interpreter evaluates the target 
expression just once instead of each repeating themselves.  (And 
consequently, any side-effects of that evaluation happen just once 
instead of twice.)  The same __xxx__ or __rxxx__ method is used in 
either case.  This non-repetition is the reason for augmented 
assigments.  The optional in-place optimization for mutables is 
secondary.  It was debated and could have been left out.

Second, all augmented assignments perform an assignment, even if the 
operation is done in place.  However, if a mutable such as a list is 
accessed as a member of an immutable collection such as a tuple, 
mutation is possible, but rebinding is not.  So the mutation is done and 
then an exception is raised.  To avoid the exception, directly call a 
mutation method such as list.extend.

Terry Jan Reedy

More information about the Python-list mailing list