Is it just Syntactic Sugar ?

Johann Hibschman johann at physics.berkeley.edu
Thu Jun 1 16:51:26 EDT 2000


Sorry for the delay, but I've been busy.

Thomas Wouters writes:

> I'll reply to this post instead of the longer one, because you *almost*
> understand my meaning now ;-) I'm not asking for a 't1[t2].incr(e)'.
> Instead, I'm asking for a method exactly like __add__ that realizes that the
> caller actually wants to replace the current object with the new object. It
> shouldn't matter [to the definition] wether the object is changed in place,
> and returns self, or creates a new object just like __add__, and returns
> that.

I understand that much; that was what I was trying to spell with my
"incr" method, an in-place increment.

Guido's __add_ab__ fits what I was talking about; his a.extend is the
same idea as my a.incr.

My problem with this proposal is more how it fits with container
objects, such as lists and dictionaries.  Actually, I think I might
have just been thick about it.  I'll try to say it again, just so you
understand where I'm coming from.

If we assume mutable types, and a magic __add_ab__ method, the most
efficient way to do "lst[i] += 1" is to get the (mutable) object
referenced by lst[i], then increment that object in place.  This will
only call the __getitem__ method of the list, and the __add_ab__
method of the mutable object.

If we have nonmutable types, we have to get lst[i], using __getitem__,
compute the incremented value, using the default __add_ab__, then put
that value back into the containter, using __setitem__.

This is the asymmetry that I was objecting to.  The only way I can see
it being resolved is to always demands he full __getitem__,
__add_ab__, __setitem__ sequence, even if redundant.  The other
option, where we only call __getitem__ and __add_ab__, doesn't seem
(to me) like it would work with the way objects work in python.  How
would __add_ab__ know where the original object came from, so it can
put the new object back in, if the object is immutable.

If you demand the full sequence of get/add/set, then it works.  The
in-place addition simply becomes an object-creation optimization, not
a way to optimize away the sequence-set operation.  Does that make
sense?

-- 
Johann Hibschman                           johann at physics.berkeley.edu



More information about the Python-list mailing list