Is it just Syntactic Sugar ?
Johann Hibschman
johann at physics.berkeley.edu
Tue May 30 17:13:44 EDT 2000
Thomas Wouters writes:
> On Tue, May 30, 2000 at 01:12:53PM -0700, Johann Hibschman wrote:
>> A simple rewrite is the only way to make sense of
>>
>> i += 1 -> i = i + 1
>> if i is an integer, given the existing python variable semantics.
> Why do you need a rewrite ? It can *function* like a rewrite for immutable
> types, and that is indeed the only way it can function. But it shouldn't be
> a macro-type rewrite by the compiler, because then you can't do an in-place
> add with mutable types. The compiler doesn't know what variable is what
> type!
A few reasons. Mostly, it's because I don't like mixing function-call
semantics with assignment semantics. If it's a simple macro, you gain
consistency, but lose the "in-place" nature of the add. If it's a
function, like '__add__' and friends, you cannot modify the binding.
If it's both, it gets ugly. What if you have a mutable sequence which
is immutable, but which defines its own methods for __getitem__ and
__setitem__? Wackiness ensues.
"i += 1" makes sense as "i = i + 1"
"l[i] += 1", however, could either be "l[i] = l[i] + 1" if l[i] is
immutable, calling __getitem__ once and __setitem__ once, or
"l[i].incr(1)" if l[i] is mutable, calling __getitem__ once and the
mutation method of l[i].
I don't like this at all. The methods called on a container object
would then depend on whether the *contents* of the container was
mutable or not.
And what if l was a tuple instead? Then "l[i] += 1" would raise an
error if l[i] were immutable, but work fine if it were mutable. This
just seems like an unholy can of worms.
A macro rewrite is at least consistent. It might not always do the
right thing, but it is simple to understand. If you want the in-place
incremention of an object, just define an "incr" method and use it.
(I would actually find it useful, to avoid long-winded things like
"self.current_spectra[i,:] = self.current_spectra[i,:] +
absorption_vector". This would work even better as an in-place
increment, admittedly, but if I were worried about that much overhead,
I wouldn't be using NumPy.)
--Johann
--
Johann Hibschman johann at physics.berkeley.edu
More information about the Python-list
mailing list