
[Tim]
I'm not sure it's "a feature" that
print [n+f() for x in range(10)]
looks up n and f anew on each iteration -- if I saw a listcomp that actually relied on this, I'd be eager to avoid inheriting any of author's code.
It's just a direct consequence of Python's general rule for name lookup in all contexts: variables are looked up when used, not before. (Note: lookup is different from scope determination, which is done mostly at compile time. Scope determination tells you where to look; lookup gives you the actual value of that location.) If n is a global and calling f() changes n, f()+n differs from n+f(), and both are well-defined due to the left-to-right rule. That's not good or bad, that's just *how it is*. Despite having some downsides, the simplicity of the rule is good; I'm sure we could come up with downsides of other rules too. Despite the good case that's been made for what would be most useful, I'm loathe to drop the evaluation rule for convenience in one special case. Next people may argue that in Python 3.0 lambda should also do this; arguably it's more useful than the current semantics there too. And then what next -- maybe all nested functions should copy their free variables? Oh, and then maybe outermost functions should copy their globals into locals too -- that will speed up a lot of code. :-) There are other places in Python where some rule is applied to "all free variables of a given piece of code" (the distinction between locals and non-locals in functions is made this way). But there are no other places where implicit local *copies* of all those free variables are taken. I'd need to find a unifying principle to warrant doing that beyond utility. --Guido van Rossum (home page: http://www.python.org/~guido/)