list to table
Alf P. Steinbach
alfps at start.no
Fri Nov 6 08:29:05 CET 2009
* Gabriel Genellina:
> En Thu, 05 Nov 2009 21:23:27 -0300, Alf P. Steinbach <alfps at start.no>
> From the docs for the operator module: "Many operations have an
> “in-place” version. The following functions provide a more primitive
> access to in-place operators than the usual syntax does; for example,
> the statement x += y is equivalent to x = operator.iadd(x, y). Another
> way to put it is to say that z = operator.iadd(x, y) is equivalent to
> the compound statement z = x; z += y."
>> foo()[bar()] += 1
>> so here it's not translated like 'foo()[bar()] = foo()[bar()] + 1' but
>> evidently more like 'a = foo(); i = bar(); a.__setitem__(i,
>> a.__getitem__(i) + 1)'?
> Yes, something like that.
>> If so, is this behavior defined anywhere?
> Isn't the description at
> enough? It goes to some detail describing, e.g., what a.x = 1 means. The
> next section explains what a.x += 1 means in terms of the former case.
No, it wasn't exactly enough for me, coming most recently from a C++ background.
One reason was as mentioned that the C++ standard has essentially the /same
wording/ about "only evaluated once" but with a more strict meaning; in C++,
with the built-in += operator
a()[foo()] += 1;
not only avoids calling a() and foo() twice, it also avoids doing the internal
indexing twice, while in python the internal indexing, locating that item, is
performed first in __getitem__ and then in __setitem__ (unless that is optimized
away at lower level by caching last access, but that in itself has overhead).
Another reason was that §6.2 does explicitly discuss attribute references as
targets, but not subscription as target. It would have been more clear to me if
all (four?) possible target forms were discussed. Happily you did now discuss
that in the part that I snipped above, but would've been nice, and easier for
for an other-language-thinking person :-), if it was in documentation.
>> I did find discussion (end of §6.2 of the language reference) of the
>> case where the target is an attibute reference, with this example:
>> class A:
>> x = 3 # class variable
>> a = A()
>> a.x += 1 # writes a.x as 4 leaving A.x as 3
> Do you want to discuss this example?
Thanks but no, it's OK, I understand it.
More information about the Python-list