Consider the following:
def f():
a = 2
b = [a + i for i in range(3)]
f()
This runs without problems. As I understand it (please correct me if I'm wrong, though), the list comprehension expression introduces a new scope, but since it is created within a function (as opposed to, say, a class), it has access to the surrounding scope, including the variable a
.
In contrast, if I were to enter debug mode, stop at line 3 above, and then just manually write the following in the interpreter
>>> b = [a + i for i in range(3)]
I get an error:
Traceback (most recent call last):
File "<string>", line 293, in runcode
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 1, in <listcomp>
NameError: global name 'a' is not defined
Why is this? When I'm stopped at a given line in debug mode, isn't the scope that I have access to the same as what it would be at runtime?
(I'm using PyScripter, by the way)