Parameterized functions of no arguments?

Carl Banks pavlovevidence at gmail.com
Fri Feb 11 00:59:30 EST 2011


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))


Carl Banks



More information about the Python-list mailing list