Python Mystery Theatre -- Episode 2: Así Fue

Fredrik Lundh fredrik at pythonware.com
Mon Jul 14 17:19:34 EDT 2003


Helmut Jarausch wrote:

> 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
*values*.

</F>








More information about the Python-list mailing list