Am 03.06.2011 01:43 schrieb Gregory Ewing:
It's not the lambda that's different from other languages,
it's the for-loop. In languages that encourage a functional
style of programming, the moral equivalent of a for-loop is
usually some construct that results in a new binding of the
control variable each time round, so the problem doesn't
arise very often.
If anything should be changed here, it's the for-loop, not
lambda.
In my opinion, it is rather the closure thing which confused me at some
time, and that's exactly what is the subject of the thread.
On one hand, a closure can be quite handy because I have access to an
"outer" vaiable even it changes.
But on the other hand, I might want to have exactly the value the
variable had when defining the function. So there should be a way to
exactly do so:
funcs=[]
for i in range(100):
def f(): return i
funcs.append(f)
for f in funcs: f()
Here, i should not be transported as "look what value i will get", but
"look what value i had when defining the function".
So there should be a way to replace the closure of a function with a
snapshot of it at a certain time. If there was an internal function with
access to the readonly attribute func_closure and with the capability of
changing or creating a cell object and thus hbeing capable of doing so,
it could be used a a decorator for a function to be "closure-snapshotted".
So in
funcs=[]
for i in range(100):
@closure_snapshot
def f(): return i
funcs.append(f)
each f's closure content cells would just be changed not to point to the
given variables, but to a cell referenced nowhere else and initialized
with the reference pointed to by the original cells at the given time.
Thomas
--
http://mail.python.org/mailman/listinfo/python-list