Odd closure issue for generators

Michele Simionato michele.simionato at gmail.com
Fri Jun 5 03:04:11 EDT 2009

On Jun 5, 6:49 am, a... at pythoncraft.com (Aahz) wrote:
> In article <05937a34-5490-4b31-9f07-a319b44dd... at r33g2000yqn.googlegroups.com>,
> Michele Simionato  <michele.simion... at gmail.com> wrote:
> >Actually, in Scheme one would have to fight to define
> >a list comprehension (more in general loops) working as
> >in Python: the natural definition works as the OP wants. See
> >http://www.artima.com/weblogs/viewpost.jsp?thread=3D251156and the
> >comments below for the details.
> This URL isn't working for me, gives 500.

Anyway, the point is that to explain Python behavior with closures in
list/generator comprehension it is not enough to invoke
late bindings (Scheme has late bindings too but list comprehension
works differently). The crux is in the behavior of the for loop:
in Python there is a single scope and the loop variable is
*mutated* at each iteration, whereas in Scheme (or Haskell or any
other functional language) a new scope is generated at each
iteration and there is actually a new loop variable at each iteration:
no mutation is involved. Common Lisp works like Python. It is a design
decision which at the end comes down to personal preference and
languages make different choices with no clear cut winner (I
prefer the more functional way).

More information about the Python-list mailing list