Normalizing A Vector

Thomas Jollans thomas at jollans.com
Sun Aug 1 06:32:19 EDT 2010


On 08/01/2010 03:41 AM, Lawrence D'Oliveiro wrote:
> In message <87sk2zhpcj.fsf at dpt-info.u-strasbg.fr>, Alain Ketterlin wrote:
> 
>> Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> writes:
>>
>>>     V = tuple \
>>>       (
>>>             x
>>>         /
>>>             l
>>>        for x in V
>>>        for l in
>>>            (math.sqrt(reduce(lambda a, b : a + b, (y * y for y in V),
>>>            0)),)
>>>       )
>>
>> You got the order wrong (it has to be for l ... for x ...)
> 
> No, I deliberately put it in that order to ensure that the value for l can 
> only ever be evaulated once.
> 
>> You're kind of lucky here, because the arglist to tuple() provides a
>> scope that hides x and l. Be careful if you ever change tuple(...) to
>> [...], because x and l would leak to the outer scope (with python 2.*).
> 
> Interesting. However, using “list( ... )” instead of “[ ... ]” also prevents 
> the leakage.

Yes. That's because the variable leakage of list comprehensions was
never a good idea, and is kept in Python 2.x only for backwards
compatibility. When generator expressions where introduced, it was done
in such a way that the scope didn't leak (which probably wouldn't make
any sense anyway since there's no guarantee a generator expression is
executed at all before the next line)

In Python 3, list comprehensions don't leak names any more - they act
(nearly?) the same as like( ... expr ... ) now.



More information about the Python-list mailing list