Odd closure issue for generators

Michele Simionato michele.simionato at gmail.com
Thu Jun 4 22:35:59 EDT 2009


On Jun 5, 1:18 am, Carl Banks <pavlovevide... at gmail.com> wrote:
> It's really the only sane way to handle it, odd though it may seem in
> this narrow case.  In Python nested functions have to be able to
> reference the current value of a variable because of use cases like
> this:
>
> def func():
>     def printx():
>         print x
>     x = 1
>     printx()
>     x = 2
>     printx()
>
> Referencing a nonlocal variable always uses the current (or last)
> value of that variable, not the value it had when the nested function
> was defined.

This is not a good argument. Counter example: Scheme works
exactly like Python

(define (func)
  (define x 1)
  (define (printx)
    (display x) (newline))
  (printx)
  (set! x 2)
  (printx)) ;; prints 1 and 2

but it is still possible to have a list comprehension working
as the OP wants:

(list-of (lambda () i) (i in (range 11 16)))

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=251156 and the
comments below for the details.



More information about the Python-list mailing list