Strange loop behavior when assigning variable within loop

question
#1

I’m confused about the following behavior:

julia> a = 2019
2019

julia> for i in 1:2
           println(i)
           println(a)
           a = 57
       end
1
ERROR: UndefVarError: a not defined
Stacktrace:
 [1] top-level scope at ./REPL[2]:3 [inlined]
 [2] top-level scope at ./none:0

I would have thought that this would have printed:

1
2019
2
57

Can someone explain where my thinking is going wrong?

#2

The relevant section in the manual is here. To be specific:

In a local scope, all variables are inherited from its parent global scope block unless:

  • an assignment would result in a modified global variable, or

In other words, since a = 57 is an assignment that would result in a modified global variable, a is not inherited from the global REPL scope, so trying to access it with println(a) results in an a not defined error.

If you want the output you suggest, you can use global a = 57 to change the global variable.

2 Likes
#3

Hmm, strange, on Juliabox using 1.0.3 this works the way I would expect though:
image

It’s only on my machine it has this error.

I ran it with --startup-file=no and even renamed the startup file to be sure it was a vanilla REPL.

Any suggestions? Why would this behavior differ between different installs of the same version of Julia?

1 Like
#4

Following up: looks like this also works in my local Jupyter install. Here’s a screenshot from an IJulia console session:
image

Seems like IJulia and the Julia REPL treat these differently for some reason?

1 Like
#5

This is the “soft global scope” problem https://github.com/JuliaLang/julia/issues/28789.

I believe the behavior in jupyter is different to the REPL because jupyter uses https://github.com/stevengj/SoftGlobalScope.jl as a workaround for the somewhat unintuitive behavior of the new scoping rules in julia-1.0. (The rules changed only for code executed at “top level” - ie outside a function.)

There’s been a lot of discussion on this forum about this particular issue which you can find if you search for things like “soft global scope”.

2 Likes
#6

I guess shoutout to this comment, as that is exactly what happened in this case: