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?
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.
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”.