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

Guido van Rossum guido at python.org
Fri Jul 11 04:58:45 CEST 2008

On Thu, Jul 10, 2008 at 2:26 PM, Raymond Hettinger <python at rcn.com> wrote:
> When exercising 2-to-3 on Zodb at the EuroPython sprints, we also found
> another oddity.  This code works in 2.6 but fails in 3.0 (it looks for the
> free variable in the global scope instead of the enclosing local scope):
> class A(object):
>   v = 8
>   x = [v for i in range(6)]

This is in a sense not new, and I believe we decided not to do
anything about it. You can get the same error in 2.6 by using a genexp
instead of a listcomp, like this:

class A:
  v = 8
  x = list(v for i in range(6))

The new failure in 3.0 is a side effect of the translation (mostly) of
list comps into genexps. The underlying problem is that the genexp
creates a function scope, and function scopes don't have access to the
surrounding class body scope. (There's a really good but extremely
subtle reason for that.)

I think there are old threads about this.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-3000 mailing list