I really don't understand Lambda!
Fredrik Lundh
fredrik at pythonware.com
Sat Oct 12 06:21:57 EDT 2002
Tim Roberts wrote:
> >So, (1) do we always need some kind of assignment between the 'lambda'
> >and the ':'?
>
> Because until Python 2.1, each lambda had its own local namespace. It
> could not see items in the outer namespace. In your example, the lambda
> would not have been able to see "wg". You had to pass it as a parameter.
>
> With the nested scopes feature in 2.1, the extra parameter is no longer
> necessary, but there's a lot of code out there that wants to be backwards
> compatible.
or more likely, there's a lot of code out there that wants to
work properly...
there's a major difference between explicit binding via default
arguments and nested scopes: the former evaluates the name
and binds to the resulting object, the latter binds to the name
itself and causes Python to look it up every time it's used.
here's a simple example; let's use a loop to create ten buttons
which all call the same callback with a different value. the first
version uses the "old" way:
def printme(value):
print value
for index in range(10):
w = Button(text=str(index), command=lambda i=index: printme(i))
w.pack()
if you click a button, the corresponding number is printed to stdout,
just as expected.
using the "new" way,
for index in range(10):
w = Button(text=str(index), command=lambda: printme(index))
w.pack()
you'll find that all buttons print "9"...
</F>
More information about the Python-list
mailing list