[Python-Dev] namespace for generator expressions
Samuele Pedroni
pedronis at bluewin.ch
Wed Feb 4 08:49:33 EST 2004
At 17:36 26.01.2004 -0500, Phillip J. Eby wrote:
>(Of course, I also often forget that free variables don't bind early in
>nested functions! It always seems strange to me that I have to write a
>function that returns a function in order to just define a function with
>bound variables. Indeed, it's hard to think of a time where I've *ever*
>wanted late binding of variables in a nested function.)
0) It should be noted that late binding makes likely the most sense when
rebinding is allowed (a feature I still don't know whether it ought to be
added, but that's beside the point). At the moment what it allows is
mutually referring or self-recursive nested definitions:
def h():
def f()
# f can refer to g
def g()
...
[ not that is totally unimagibable a semantics where:
def f():
x = 1
def g(): return x
x = 2
return g()
def f():
def g(): return x
x = 1
x = 2
return g()
both return 1 ... ]
1) we suffer a bit more the late binding semantics because creating a new
scope is not a lightweight operation in Python, consider this Common Lisp code:
> (defun f ()
(do ((x 0 (+ x 1))
(lst () (append lst (list (lambda () x)))))
((= x 4) lst)))
> (mapcar #'funcall (f))
(4 4 4 4)
kind of like:
def f():
x = 0
lst = []
while not (x == 4):
lst.append(lambda : x)
x += 1
return lst
>>> [ el() for el in f() ]
[4, 4, 4, 4]
an inline 'let' makes it do the what's maybe expected:
>(defun f ()
(do ((x 0 (+ x 1))
(lst () (append lst (list (let ((x x)) (lambda () x))))))
((= x 4) lst)))
> (mapcar #'funcall (f))
(0 1 2 3)
In Scheme both 'do' and named-let directly introduce a fresh scope per
iteration:
(define (f)
(do ((x 0 (+ x 1))
(lst ()
(append lst (list (lambda () x)))))
((= x 4) lst) ))
> (map (lambda (func) (func)) (f))
(0 1 2 3)
regards.
More information about the Python-Dev
mailing list