Lambda Scoping

Michael Gilfix mgilfix at eecs.tufts.edu
Mon Apr 29 11:14:08 EDT 2002


  Lambdas in python don't work exactly like lambdas that you would
expect in lisp. The scoping is a little different. To make this work,
you need to do something like this:

    lambda i=instance: i

  Which does an assignment to i when the lambda function is created
and gets carried around with the function.

  As for the merits of lambdas, well, you might want to read some
other threads being posted today :)

               -- Mike

On Mon, Apr 29 @ 15:02, Gerson Kurz wrote:
> The following code
> ...
> funcs = []
> for instance in range(10):
>     funcs.append( lambda: instance )
> print map(apply,funcs)
> 
> funcs = []
> for instance in range(10):
>     funcs.append( lambda instance=instance: instance )
> print map(apply,funcs)
> ...
> prints
> 
> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> 
> which I sort-of understand (I figure, in "lambda: instance" instance
> is a lazy expression; "lambda instance=instance: instance" the
> expression itself - "instance" - is a lazy expression, too, but the
> argument list is not.) However, can anybody please explain this more
> detailed? 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
`-> (gerson.kurz)

-- 
Michael Gilfix
mgilfix at eecs.tufts.edu

For my gpg public key:
http://www.eecs.tufts.edu/~mgilfix/contact.html





More information about the Python-list mailing list