Python Mystery Theatre -- Episode 2: Así Fue

Jack Diederich jack at performancedrivers.com
Mon Jul 14 16:48:55 EDT 2003


On Mon, Jul 14, 2003 at 10:13:08PM +0200, Helmut Jarausch wrote:
> Raymond Hettinger wrote:
> > ACT III ----------------------------------------------------
> > def once(x): return x
> > def twice(x): return 2*x
> > def thrice(x): return 3*x
> > funcs = [once, twice, thrice]
> > 
> > flim = [lambda x:funcs[0](x), lambda x:funcs[1](x), lambda x:funcs[2](x)]
> > flam = [lambda x:f(x) for f in funcs]
> > 
> > print flim[0](1), flim[1](1), flim[2](1)
> > print flam[0](1), flam[1](1), flam[2](1)
> 
> OK, I believe to know why the last line
> print '3' three times, since only a reference
> to 'f' is stored within the lambda expression
> and this has the value 'thrice' when 'print'
> is executed.
> But how can I achieve something like an
> evaluation of one indirection so that
> a reference to the function referenced by 'f'
> is stored instead.

The problem is made up to make a point, just doing
flam = funcs
will do the right thing.  If you really want to wrap the function in a list
comp, you could do

def wrap_func(func):
  return lambda x:func(x)

flam = [wrap_func(f) for (f) in funcs] # wrap during a list comp
flam = map(wrap_func, funcs) # the map() equivilent

more awkward versions of the above:

wrap_func = lambda func:lambda x:func(x)
flam = [(lambda func:lambda x:func(x))(f) for f in funcs]

-jack





More information about the Python-list mailing list