[Python-ideas] Changing semantics of for-loop variable
Jason Orendorff
jason.orendorff at gmail.com
Tue Oct 4 16:02:54 CEST 2011
On Tue, Oct 4, 2011 at 7:22 AM, Ronald Oussoren <ronaldoussoren at mac.com> wrote:
> What worries me with this proposal is that it only affects the loop variable, and not other variables.
Right. Another similar example:
def f1(seq):
for i in seq:
yield lambda: i.name # each lambda refers to a different i
def f2(seq):
for i in seq:
x = i.name
yield lambda: x # each lambda refers to the same local x
Think of f2 as a refactoring of f1. I think the programmer has a right
to expect that to work, but it would change behavior in a really
surprising way.
Also: What if the loop variable is also used elsewhere in the function?
def f(seq):
i = None
for i in seq:
pass
return i
Does the loop variable get a cell in this case? If so, I guess it must
be a different variable from the local i. So would f([1]) return None?
That would be a rather astonishing change in behavior!
So perhaps the loop variable cell would be kept in sync with the local
variable during the loop body? It all seems too weird.
-j
More information about the Python-ideas
mailing list