functional programming and default parameters

Tim Peters tim_one at email.msn.com
Fri Jun 29 14:16:49 EDT 2001


[Ralf Muschall]
> ...
> Unfortunately, in Python writing
>
> for i in range(3):
>   j=i
>   fns[i]()=lambda:j
>
> fails, and even this fails too:
>
> for i in range(3):
>   j=i+10
>   a[i]=lambda:j
>
> map(x:x(),fns) gives [12,12,12].

"for" doesn't create a new scope in Python:  in both examples, *everything*
is taking place in the same namespace (scope).  "lambda: j" compiles to a
code block that returns the current binding of the non-local name j,
whatever that happens to be when the body of the lambda is executed.
Because the loop didn't create a new scope, assigning to j inside the loop
has nothing to do with the value the lambda returns at *its* runtime.

> My guess is that the interpreter detects the *creation* of the
> variable "j" in the loop and optimizes by shifting that in front of
> the loop, leaving only the *assignment* in the loop body.

No, Python does no optimizations at all:  WYSIWYG.  But you're carrying a
scope model over from Lisp that doesn't apply in Python.  In general, the
only way to get a Lispish new scope in Python is via nesting a def.





More information about the Python-list mailing list