[Python-3000] Is this a bug with list comprehensions or not?

Stefan Behnel stefan_ml at behnel.de
Sat Jul 12 06:37:29 CEST 2008

Raymond Hettinger wrote:
> I know this group doesn't care about Psyco, but it was
> nice that psyco could handle listcomps just like it could with
> regular for-loops.  Turning it into a genexp stops psyco in its tracks.
> Likewise, Cython won't be able to handle the semantics.

Regarding Cython, I expect that we will be able to implement this pretty soon,
by translating the generator expression into an iterable extension class with
local variables.

However, such an approach will obviously be a lot slower than a plain embedded
C loop for literal list/tuple/set comprehension (as we currently generate for
list comprehensions). So a better approach might be to actually apply a
separate scoping rule to the iteration variable, such as renaming it into
something that just can't be retrieved from the outside world. That way, it
would still be available to everything inside the comprehension, but it can't
leak anymore.

The only semantic difference I see with this is:

    >>> def test():
    ...     return [locals()['x'] for x in range(10)]
    >>> test()
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

This actually works in Py3k, although I wonder if it really should work...


More information about the Python-3000 mailing list