[Python-Dev] Possible resolution of generator expression
variablecapture dilemma
Tim Peters
tim.one at comcast.net
Thu Mar 25 00:30:44 EST 2004
BTW, have we had an example of a generator expression where late binding was
semantically necessary? The only one I recall was a strained one along the
lines of:
sqs = (sq(i) for i in range(n))
def sq(i):
return i**2
Late binding was needed then because the generator expression referenced a
name not yet bound when the g-e was evaluated.
Is the popular plan now that this "will work", but provided that "n" is
bound before the g-e is evaluated? That is, this works:
n = 10
sqs = (sq(i) for i in range(n))
def sq(i): ...
print list(sqs)
but this doesn't work:
sqs = (sq(i) for i in range(n))
n = 10 # swapped with the line above
def sq(i): ...
print list(sqs)
and this uses different bindings for the two lexical instances of "n" in the
g-e:
n = 10
sqs = (sq(i+n) for i in range(n) # 10 used in range(n), 20 in i+n
n = 20
def sq(i): ...
print list(sqs)
?
Not wondering how bad it can get, just wondering how bad it starts <wink>.
More information about the Python-Dev
mailing list