List comprehensions now use a function scope, that was a change between Python 2 and 3. The variable pre
will be inaccessible from within the list comprehension for this reason.
The new behavior is documented under the execution model (emphasis mine), with an example given that is very similar to the one you have found:
Class definition blocks and arguments to exec()
and eval()
are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope. This means that the following will fail:
class A:
a = 42
b = list(a + i for i in range(10))
Furthermore, pre
name will also be inaccessible via the class XY.pre
, because the class doesn't exist yet. You will have to find another way to go about what you want to do.