This code (a simplified example from the real code) works:
class A:
data = ' '
remains = [c for c in data]
The following code produces NameError: name 'data' is not defined:
class A:
data = ' '
remains = [c for c in data if c in data]
I created an issue on the Python bugtracker and the answer was a link to the “Naming and Binding” section of the docs where it says:
Class definition blocks and arguments to
exec()andeval()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.
I understand this definition. But - and this is a big “but” - if it is like this, shouldn’t the first code example also trigger an error?