inconsistency with += between different types ?
Andreas Leitgeb
Andreas.Leitgeb at siemens.at
Wed Aug 7 16:06:42 EDT 2002
Christopher A. Craig <list-python at ccraig.org> wrote:
>> Immutable objects don't have to implement __iadd__ et al. at
>> all and in fact ints don't have __iadd__. Python falls back to calling
>> __add__ and normal assignment automatically.
> While this is true, "fixing" __iadd__ as he requested and retaining
> that behavior wouldn't solve the problem he is trying to address
I suppose, I am the "he" addressed :-)
Meanwhile, I have (so I think) a clear idea about the interconnectedness
of += , __iadd__ and __add__ (and all the other ..=, __i...___,__...__)
currently:
x+=y means:
if __iadd__ defined :
call x.__iadd__(y) # (which is supposed to change x in-place), then
re-assign the result to x
# (in the normal case, the final assignment does nothing, because
# "x" (outside) and the return'ed self (from inside) refer to the
# same object.
# otherwise it most likely causes problems (see: pitfall).)
elif __add__ defined:
call x.__add__(y) # (which is supposed NOT to change x in-place) and
assign the result to x
# (possible free'ing the object that was previously referenced by x.)
else: raise some error # no addition defined
the suggestion:
x+=y should mean:
if __iadd__ defined :
just call x.__iadd__(y) and let it modify x as it pleases
# nothing else, return value is to be ignored.
# or perhaps warned about, if it is neither None nor self,
# which would indicate a legacy dirty use.
elif __add__ defined:
... # just like it is now. no change in behaviour in this branch
else: raise some error # ...
I hope, it is clear now, what I had in mind with that suggestion, so
we can start discussing the point, rather than speculating about
wrong motivations (,which was generally not a bad thing, *initially*, btw.)
PS: the only (and very weak) counter-argument would be, if some
class wanted to decide at runtime, whether to behave like immutable
or not, but this effect could still be achieved by storing away the
__i...__ methods into a local dict, and writing them back if the object
should behave mutably again -- not a very likely scenario, anyway.
--
class number:
def __add__(self,x):
if self.val+x>4: return 'A bright suffusion of yellow'
else return self.val+x
More information about the Python-list
mailing list