Reading and writing a global variable

Please consider the following code:

module MyModule
    global MY_GLOBAL = 42
    
    function test()::Nothing
        println("MY_GLOBAL ", MY_GLOBAL)
        
        # MY_GLOBAL = 3
        return nothing
    end
end # MyModule

MyModule.test()

As is, this code just runs and MY_GLOBAL is in scope for reading. Now if the line MY_GLOBAL = 3 is commented back in, the script fails on the line with the println call - which it could execute before. The error is ERROR: LoadError: UndefVarError: MY_GLOBAL not defined. Of course, adding global MY_GLOBAL in the function makes the code run, but that is not the point. IMHO, a variable is in scope in a function or not and that should not depend on read or write attempts. What is going on?

Inside a function scope, Julia first looks for all new assignments.

If an there is an assignment which shares the same name as a global variable, it treats all references to that variable as local, even ones that happen before the assignment.

This creates somewhat confusing errors, for sure.

2 Likes

Just for the record, Python works exactly the same in this case:

my_global = 42

def fun():
     print(my_global)
     # Fails if line below is uncommented
     # my_global = 3

fun()
1 Like