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


Groups > comp.lang.python > #55513

Re: Parameterized functions of no arguments?

From Arnaud Delobelle <arnodel@gmail.com>
Newsgroups comp.lang.python
Subject Re: Parameterized functions of no arguments?
References <ij2fdr$uo7$1@news.eternal-september.org> <ij2ha2$kss$1@news.eternal-september.org> <7xvd0rm6sy.fsf@ruckus.brouhaha.com> <ij2l70$vn9$1@news.eternal-september.org>
Message-ID <87ei7favyr.fsf@gmail.com> (permalink)
Organization virginmedia.com
Date 2011-02-11 07:09 +0000

Show all headers | View raw


Rotwang <sg552@hotmail.co.uk> writes:

> On 11/02/2011 06:19, Paul Rubin wrote:
>> Rotwang<sg552@hotmail.co.uk>  writes:
>>>      menu = Tkinter.Menu(master, tearoff = 0)
>>>      for k in x:
>>>          def f(j = k):
>>>              [do something that depends on j]
>>>          menu.add_command(label = str(k), command = f)
>>>
>>> Still, I'd like to know if there's a more elegant method for creating
>>> a set of functions indexed by an arbitrary list.
>>
>> That is a standard python idiom.  These days maybe I'd use partial
>> evaluation:
>>
>>     from functools import partial
>>
>>     def f(k):  whatever...
>>
>>     for k in x:
>>        menu.add_command(label=str(k), command=partial(f, k))
>
> functools is new to me, I will look into it. Thanks.
>
>
>> the "pure" approach would be something like
>>
>>     def f(k):  whatever...
>>
>>     for k in x:
>>       menu.add_command(label=str(k),
>>                        command=(lambda x: lambda: f(x))(k))
>
> I don't understand why this works. What is the difference between
>
>     (lambda x: lambda: f(x))(k)
>

The value of k is bound to the local variable x; If k is changed later,
it doesn't affect the value of x above

Note that you can also write it:

    lambda k=k: f(k)

> and
>
>     lambda: f(k)
>
> ?

K not being local, If k is changed later, it does affect the above.

-- 
Arnaud

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


Thread

Re: Parameterized functions of no arguments? Arnaud Delobelle <arnodel@gmail.com> - 2011-02-11 07:09 +0000

csiph-web