Why do function variables behave differently than global script variables?

In your first example, a inside and outside the loop are different variables; and the a outside is a global variable (i.e. defined in global scope, i.e. to top level of a module or at >> in the REPL). The rule is:


    an assignment would result in a modified global variable, or
    a variable is specifically marked with the keyword local.

Thus global variables are only inherited for reading, not for writing

https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Local-Scope-1

Thus because the assignment would “result in a modified global variable” a new local variable is introduced. And because a += 1 also accesses this new a before its assignment it errors.

Example 2 works because you specifically tell Julia to use the global a.

Example 3 works because the outer a is not a global but also local. Then above rules don’t apply and a can be written to.

BTW, this was quite a controversial change late towards stabilizing Julia 1.0, see Another possible solution to the global scope debacle. Also, note that Jupyter notebooks handle this differently, there your example 1 works due to using SoftGlobalScope.jl.

4 Likes