Path: csiph.com!eeepc.pasdenom.info!news.pasdenom.info!news.dougwise.org!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!feeder.news-service.com!cyclone03.ams2.highwinds-media.com!news.highwinds-media.com!npeersf01.ams.highwinds-media.com!newsfe29.ams2.POSTED!00000000!not-for-mail From: Arnaud Delobelle Newsgroups: comp.lang.python Subject: Re: Parameterized functions of no arguments? References: <7xvd0rm6sy.fsf@ruckus.brouhaha.com> Message-ID: <87ei7favyr.fsf@gmail.com> User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:Tj7Ydj+1kwebtGdgNz2oWVBAWEU= MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Lines: 56 NNTP-Posting-Host: 92.236.165.220 X-Complaints-To: http://netreport.virginmedia.com X-Trace: newsfe29.ams2 1297408172 92.236.165.220 (Fri, 11 Feb 2011 07:09:32 UTC) NNTP-Posting-Date: Fri, 11 Feb 2011 07:09:32 UTC Organization: virginmedia.com Date: Fri, 11 Feb 2011 07:09:32 +0000 Xref: csiph.com comp.lang.python:55513 Rotwang writes: > On 11/02/2011 06:19, Paul Rubin wrote: >> Rotwang 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