inconsistency with += between different types ?

Andreas Leitgeb Andreas.Leitgeb at siemens.at
Wed Aug 7 11:43:47 CEST 2002


Huaiyu Zhu <huaiyu at gauss.almadan.ibm.com> wrote:
> Andreas Leitgeb <Andreas.Leitgeb at siemens.at> wrote:
>>Huaiyu Zhu <huaiyu at gauss.almadan.ibm.com> wrote:
>>> That's what it should be.  Yet it is possible for whoever writes __iadd__ to
>>> define it the other way.  
>>Is there something I've missed, or [...]

> The thing missing is that the return statement plays an unnecessarily big
> role here.  
> ...  if you define __iadd__, by
> returning an object other than self.
> By the way, if you forget to return self, you rebind the name to None.

Thanks, now (I think) I finally got it:
__iadd__ is SUPPOSED to modify self's attributes and then "return self"

If __iadd__ does return anything else than self, then it actually
breaks the intended semantics for __iadd__, but not the syntax - 
it's still legal python.

This of course explains, why it causes that much trouble.
A possible path to change this situation might be as follows: 
(Although I feel too new at Python to actually propose a change :-)
  Automatically treat a None returnvalue from an __ixxx__-method as self
  Issue a Warning, if __ixxx__ returns anything else than self or None
  Ignore the return-value altogether.
Each of these steps might have to wait for a major-version-step in
Python.
This would make sure that clean implementations would stay ok, while
those implementations, that obfuscate the design of <op>= will hopefully
phase out.

> class A:
>   def __iadd__(self,x): print x
Good demonstration of a nasty pitfall.

-- 
Newsflash: Sproingy made it to the ground !
  read more ... <http://avl.enemy.org/sproingy/>



More information about the Python-list mailing list