puzzled by name binding in local function
Dave Angel
davea at davea.name
Wed Feb 6 09:37:07 EST 2013
On 02/06/2013 05:19 AM, Ulrich Eckhardt wrote:
> Dave and Terry,
>
> Thanks you both for your explanations! I really appreciate the time you
> took.
>
> Am 05.02.2013 19:07, schrieb Dave Angel:
>> <snip>
>
>> The main place where I see this type of problem is in a gui, where
>> you're defining a callback to be used by a series of widgets, but you
>> have a value that IS different for each item in the series. You write a
>> loop much like you did, and discover that the last loop value is the
>> only one used. The two cures above work, and you can also use lambda
>> creatively.
>
> Careful, lambda does not work, at least not easily! The problem is that
> lambda only creates a local, anonymous function, but any names used
> inside this function will only be evaluated when the function is called,
> so I'm back at step 1, just with even less obvious code.
>
>
> Greetings!
>
> Uli
>
>
I haven't been able to reconstruct it exactly, but here's the function
equivalent:
def myfunc2(i):
def myfunc2b():
print ("myfunc2 is using", i)
return myfunc2b
funcs = []
for i in range(5):
funcs.append(myfunc2(i))
print "Now doing the loop2"
for func in funcs:
func()
--
DaveA
More information about the Python-list
mailing list