lambda trouble

Jacek Generowicz jacek.generowicz at cern.ch
Mon Mar 22 04:34:39 EST 2004


Darabos Daniel <cyhawk at sch.bme.hu> writes:

> Do you have some advice for me?

I'll write the concise outline in words here. If you want a more
detailed explanation, then you could do worse than reading the thread
suggested by Michele. Therein he and I go into quite some
(excruciating and graphic :-) detail of what is going on.

The original problem is that there is a single binding of "i" which is
shared by all the lambdas you shove into "l". You want each lambda to
have its own, separate, binding of "i". To do this, you need to create
a new scope which binds "i" (originally, all the lambdas find "i" in
an outer scope). In Python, the only way to create a new nested scope
is with functions (which includes lambdas); any local variables in a
function are bound in a new inner scope. You sholuld create an i which
is local to your function (lambda), and bind it to the value you want.

For example:

  lambda i=i: p(i)

Notes:

"i=i" means "i is a parameter (hence also a local variable) whose
default value is 'i at the time of function creation'" ...

... therefore, the lambda now has its own "i", which is bound to the
value of the outer "i" at the time that the lambda form is being
evaluated.



More information about the Python-list mailing list