[Python-ideas] free variables in generator expressions

Arnaud Delobelle arno at marooned.org.uk
Thu Dec 13 08:08:53 CET 2007


On 12 Dec 2007, at 23:41, Georg Brandl wrote:

> Arnaud Delobelle schrieb:
>
>> Let's test this (python 2.5):
>>
>>>>> A = '12'
>>>>> B = 'ab'
>>>>> gen = (x + y for x in A for y in B)
>>>>> A = '34'
>>>>> B = 'cd'
>>>>> list(gen)
>> ['1c', '1d', '2c', '2d']
>>
>> So in the generator expression, A is remains bound to the string '12'
>> but B gets rebound to 'cd'.  This may make the implementation of
>> generator expressions more straighforward, but from the point of view
>> of a user of the language it seems rather arbitrary. What makes A so
>> special as opposed to B?  Ok it belongs to the outermost loop, but
>> conceptually in the example above there is no outermost loop.
>
> Well, B might depend on A so it can't be evaluated in the outer  
> context
> at the time the genexp "function" is called. It has to be evaluated
> inside the "function".

You're right. I expressed myself badly: I was not talking about
evaluation but binding.  I was saying that if the name A is bound to
the object that A is bound to when the generator expression is
created, then the same should happen with B.

-- 
Arnaud





More information about the Python-ideas mailing list