Parameterized functions of no arguments?

Rotwang sg552 at hotmail.co.uk
Fri Feb 11 07:25:35 CET 2011


On 11/02/2011 05:59, Carl Banks wrote:
> Rotwang wrote:
>> On 11/02/2011 04:54, Rotwang wrote:
>> Mmmmnngh, that obviously wasn't going to work. Here's something that
>> does work:
>>
>>       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.
>
> If you don't want to use keyword arguments you can define a helper
> function to help create your closure:
>
> def create_menu_command(j):
>      def f():
>          do_something_that_depends_on(j)
>      return f
>
> for k in x:
>      menu.add_command(label=str(k),command=create_menu_command(k))

Nice, thanks.




More information about the Python-list mailing list