inconsistency with += between different types ?

Andreas Leitgeb Andreas.Leitgeb at
Thu Aug 8 08:09:32 EDT 2002

Daniel Fackrell <unlearned at> wrote:
> I've been following this thread, but I don't think I understand where the
> pitfall is.

IMO, the pitfall is unintuitivity:

 Semantically, there is a difference between functions and procedures.
 Even in Python, there are function-contexts (where only expressions
 are allowed), and statement-contexts (where also "procedures", such as
 print,del,x+=y,x=y,...) are allowed.
 now  x+=y  is not an expression, but a statement, modifying the binding
 (or the bound value) of x.   "x+=y" doesn't itself return a value.

 __add__ is, (as is operator+(...) in C++) , the "backend" of the 
   "+"-operation,  just like __iadd__ is the (primary) "backend" of
   the "+="-operation (despite the fallback added as "syntactic sugar".)

 Thus, *intuitively*, __iadd__ would be supposed to modify it's object
   in place, with no nead to return anything, (except, perhaps, the object
   itself to allow for chaining: x.__iadd__(y).__imul__(z) ...)

 *Practically*, __iadd__ can return anything, even an object of completely
   different type, that would then replace the object for which += was 
   invoked.  How high do we actually value this freedom, as opposed to
   protecting the programmer from "frequently made mistakes" ?

   Btw. Python has lots of features to protect from certain mistakes,
   (e.g. it throws an error, if I pass fewer arguments to a function
   than the function has non-optional arguments, although it could 
   just as well fill up the chain with None's)

The point is:  do we want python to protect us from (more or less 
 obvious) mistakes, or should Python get in our way as little as
 possible, always assuming perfect programmers who know what they're 
 doing  ?

> I'm not aware of any cases yet where someone has abused __iadd__ in a way
> that caused considerable confusion.
It's enough to forget the "return self" at the end, to be faced
with an error, that occurs at places, where usually one doesn't
count with them.

> Didn't your original post request information about why the built-in
> immutables and the built-in mutables behaved differently for += ?  
Yes, that happened to be the reason at that time, but thanks to this
helpful newsgroup I now have some more insight into python than at
the time I started this thread :-)

> That would still be the case after your proposed change, due to the 
> fact that if __iadd__ doesn't exist, __add__ is used in its place.
Of course, and it's good so :-)

Newsflash: Sproingy made it to the ground !
  read more ... <>

More information about the Python-list mailing list