To my surprise, in Python 3 (but not 2), this code throws a NameError
:
class Test:
n = ["1"]
[ n[i] for i in range(1) ]
gives
[ n[i] for i in range(1) ]
NameError: name 'n' is not defined
The problem is that the scope used to execute the n[i]
is a new local scope and can't see the class variables (just like you couldn't see them in a function definition). But, according to the docs
The class’s suite is then executed in a new execution frame (see Naming and binding), using a newly created local namespace and the original global namespace
This seems to me to suggest that during the execution of the list comprehension expression the class variables should just look like variables in an enclosing scope and so be suitably accessible. But not so.
Python 3.7.2
What gives?