Odd closure issue for generators

Brian Quinlan brian at sweetapp.com
Fri Jun 5 16:36:32 CEST 2009


Ned Deily wrote:
> In article <4A28903B.4020301 at sweetapp.com>,
>  Brian Quinlan <brian at sweetapp.com> wrote:
>> Scott David Daniels wrote:
>> [snipped]
>>> When you evaluate a lambda expression, the default args are evaluated,
>>> but the expression inside the lambda body is not.  When you apply that
>>> evaluated lambda expression, the expression inside the lambda body is
>>> is evaluated and returned.
>> But that's not really the issue. I knew that the lambda was not 
>> evaluated but thought each generator expression got its own context 
>> rather than sharing one.
> 
> Each?  Maybe that's a source of confusion.  There is only one generator 
> expression in your example.
> 
>>>> c = (lambda : i for i in range(11, 16))
>>>> c
> <generator object <genexpr> at 0x114e90>
>>>> d = list(c)
>>>> d
> [<function <lambda> at 0x119348>, <function <lambda> at 0x119390>, 
> <function <lambda> at 0x1193d8>, <function <lambda> at 0x119420>, 
> <function <lambda> at 0x119468>]
> 

Sorry, I wasn't as precise as I should have been.

If you consider this example:
(<expr> for x in y)

I thought that every time that <expr> was evaluated, it would be done in 
a new closure with x bound to the value of x at the time that the 
closure was created.

Instead, a new closure is created for the entire generator expression 
and x is updated inside that closure.

Cheers,
Brian



More information about the Python-list mailing list