inconsistency with += between different types ?

Donn Cave donn at u.washington.edu
Wed Aug 7 22:00:08 CEST 2002


Quoth huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu):
...
| This is not true.  There are two confusing things about the current +=
| implementation.
|
| (1) it allows immutable objects to get x=x+y semantics automatically.
|
| (2) it allows classes to define __iadd__ with a semantics that is neither
|     in-place, nor equiv to (1) above.  In particular, if you forget return,
|     you get this behavior.
|
| The second is a nasty behavior without much practical value.  What Andreas
| proposed only removes (2), while leaving (1) intact.  Even if you strongly
| advocate retaining (1) for pragmatical reasons, IMHO you should still
| support removing (2), simply for the reason of making (1) much less
| confusing to use.
|
| Once that's done, the documentation could be as simple as:
|
|   If __iadd__ is defined, x+=y changes x in place as per x.__iadd__(y).
|   Otherwise x+=y has a semantics similar x=x+y, except that x is only
|   evaluated once.
|
| In contrast, I'd challenge anyone to explain the current += behavior in less
| than twice that many words without misleading casual readers.

But that isn't really the best documentation either.  I mean,
what if we document x + y as ``whatever x.__add__(y) may do?''
Somehow you need to define under what circumstances you would
expect one behavior, vs. the other.  If you retreat to the
implementation for that, then you're saying you don't know unless
you're familiar with the implementation - does it have __iadd__
or not?  May as well require you to know what __iadd__ does.

| I'd also like to see anyone showing real use for the behavior (2).
|
| The fact that more than half of the posters in this thread did not realize
| that (2) is a possible behavior and is different from (1) demonstrates how
| counter-intuitive (2) really is.

Well, in their defense, I don't think for a minute that Jonathan
Hogg for example didn't realize this.  I understood him to be
speaking from the point of view of how __iadd__ ought to be
implemented, as opposed to the theoretical possibility that it
could confound you by doing something else.

But I don't agree with that, either.  As long as += has a rebinding
effect in some cases, I think that's a legitimate implementation
decision.  For example, I'm surprised that UserString modifies in
place.  In general, one may want to pass data to functions without
exposing the data to modification, avoiding side effects, and a
non-modifying __iadd__ would be part of how you'd do that without
making it difficult for the function to use the data in calculations.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list