inconsistency with += between different types ?
huaiyu at gauss.almadan.ibm.com
Thu Aug 8 21:15:38 CEST 2002
Donn Cave <donn at u.washington.edu> wrote:
>Quoth Andreas.Leitgeb at siemens.at (Andreas Leitgeb):
>| Because += already has this fallback to __add__ builtin, __iadd__
>| shouldn't care about the immutable case. It need not even exist for
>| that case. Now for the mutable case, it should be __iadd__'s only
>| job to get the mutation done on the object.
>This would force the programmer to rely on the absence of __iadd__
>to implicitly get the desired behavior. It's clearer (and faster,
>cf. Timothy Delaney's followup) to make it explicit.
Readability. It is not clear to me that what we have is more explicit.
IMHO it is more explicit to have a strict rule:
- with __iadd__, always use the same object
- without __iadd__, always use __add__.
It can be argued for the symbol += to have two different semantical meanings
for pragmatic reasons. But I do not see why (for readability) the magic
methods for these two semantics have to be mixed up this way. Python does
not have a convention of one-one correspondence between operators and magic
methods. Consider those relating to 'in', 'for', etc, for example. Even
better is to use two different symbols to make these two semantics explicit.
Implementation. Even though (logically) __iadd__ does not make sense for
immutable types, the proposal does not forbid it. Nor does it require an
extra check for mutability. It only removes the final step of rebinding the
return value. It is a strict reduction of current implementation. The
complaints about increased code size appear to be misplaced.
Functionality. The only valid argument againt the proposal would be an
actual demonstration that the final rebinding is useful in some cases. No
such examples have appeared. In contrast, there is example that accidental
use of the rebinding is a pitfall.
Performance. Timothy's explanation of the look up and fall back appears to
be the only valid reason against the proposal. On the other hand, it also
reveals the real cost of mixing up these two semantics under the same
symbol. There are other ways to solve this problem. One is splitting the
two semantics into two symbols like += and +!, for example. Another is to
allow a definition like __iadd__=None to indicate the rebinding semantics,
for example. No doubt there are other approaches.
More information about the Python-list