Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #38279

Re: puzzled by name binding in local function

Date 2013-02-06 09:37 -0500
From Dave Angel <davea@davea.name>
Subject Re: puzzled by name binding in local function
References <jek7u9-aaq.ln1@satorlaser.homedns.org> <mailman.1374.1360087665.2939.python-list@python.org> <fbn9u9-9fv.ln1@satorlaser.homedns.org>
Newsgroups comp.lang.python
Message-ID <mailman.1412.1360161459.2939.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

puzzled by name binding in local function Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-05 16:18 +0100
  Re: puzzled by name binding in local function Dave Angel <davea@davea.name> - 2013-02-05 13:07 -0500
    Re: puzzled by name binding in local function Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-06 11:19 +0100
      Re: puzzled by name binding in local function Dave Angel <davea@davea.name> - 2013-02-06 09:37 -0500
        Re: puzzled by name binding in local function Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-07 09:59 +0100
  Re: puzzled by name binding in local function Terry Reedy <tjreedy@udel.edu> - 2013-02-05 14:27 -0500

csiph-web