Class Variable Access and Assignment

Christopher Subich csubich.spam.block at
Fri Nov 4 18:15:46 CET 2005

Antoon Pardon wrote:
> Well maybe because as far as I understand the same kind of logic
> can be applied to something like
> lst[f()] += foo
> In order to decide that this should be equivallent to
> lst[f()] = lst[f()] + foo.
> But that isn't the case.

Because, surprisingly enough, Python tends to evaluate expressions only 
once each time they're invoked.

In this case, [] is being used to get an item and set an item -- 
therefore, it /has/ to be invoked twice -- once for __getitem__, and 
once for __setitem__.

Likewises, lst appears once, and it is used once -- the name gets looked 
up once (which leads to a += 1 problems if a is in an outer scope).

f() also appears once -- so to evaluate it more trhan one time is odd, 
at best.

If you know very much about modern lisps, it's similar to the difference 
between a defun and a defmacro.

More information about the Python-list mailing list