Python Mystery Theatre -- Episode 2: Así Fue
vze4rx4y at verizon.net
Tue Jul 15 04:12:51 CEST 2003
> > 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.
> assuming you meant "the function reference by 'f' when the lambda
> is created", the easiest solution is to use default argument binding:
> flam = [lambda x,f=f: f(x) for f in funcs]
> the "f=f" construct will bind the inner name "f" to the current value of
> the outer "f" for each lambda.
> the nested scopes mechanism is often introduced as the "right way" to
> do what was done with argument binding in earlier versions of Python.
> however, nested scopes bind *names*, while argument binding binds
This is an excellent explanation of what was being demonstrated.
More information about the Python-list