Debugging in VS Code has difference variable scope behavior

I am trying to debug some code and upon some experimentation it seems that the debugger in visual studio code has a different scoping behavior than when running stuff no the REPL? Consider the following example (maybe I am missing something either on the behavior of the REPL or the debugger)

a = 1
b = 2

i = 0
while i < 2
    i += 1

When I run this on the repl, it runs fine. When I run it on the debugger, I get

Exception has occurred: UndefVarError

UndefVarError: i not defined

It seems that the repl behavior automatically refers to the global variable i, but this is not the case in the debugger?
Any clarification is appreciated.

Your problem might be related to global vs. non-global scope.

A helpful resource is the scope page in the official documentation.

And more precisely, you can look in that page for the difference in behavior of “soft scopes” between “interactive contexts” (like the REPL) and “non-interactive” ones (like running — or in the OP’s case case debugging — files). There is a section dedicated to the motivation for such soft scopes.

It’s unfortunate that while debugging a file, VS Code displays the error message copied by @msena , but it does not show the clarifying warning that is seen if you try to run the file in the REPL (non-interactively):

┌ Warning: Assignment to `i` in soft scope is ambiguous because a global
variable by the same name exists: `i` will be treated as a new local.
Disambiguate by using `local i` to suppress this warning or `global i` to assign
to the existing global variable.
1 Like

But why does the debugger recognize the global variable a but not the global variable i?

Because a is “read” but not assigned in the loop, so it assumes that it must be something defined outside (there is no other possibility). On the other hand, i is assigned inside the loop (i += 1 is the same as i = i + 1), so the rules presented in the cited page apply:

1 Like

Or put it another way: the problem is not that the global variable i is not recognized, but that a local i is also created (by the assignment operation i = <something>), and it shadows the existing global. So i = i + 1 is interpreted as "take the value of local i, sum 1 and put that result into local i". But the first part "take the value of local i" cannot be done, because it was not yet defined.

Perhaps you were confused by getting an UndefVarError, taking it as if it meant that global i is undefined. But that’s not the point. It is the undefined local i what triggers that error. The warning cited above may help to understand it, but unfortunately you couldn’t see it in the debugger.

Thanks @heliosdrm , this is very helpful!