Module with global variables vs initialization with `__init__` function

Quick query about modules.

Is there any difference between writing a module with initialized global variables and using an __init__ function to initialize those variables?

Allow me to explain with two demonstrations modules:

# ModuleA.jl

module ModuleA

global gCache = Dict()

end
# ModuleB.jl

module ModuleB

function __init__()
    global gCache
    gCache = Dict()
end

end

I’m curious as to whether there is any material difference between these two codes.

In addition, there is an auxillary point related to VS Code and the Julia Extension.

  • In the case of ModuleA, the Julia Extension recognizes the variable gCache
  • In the case of ModuleB, the Julia Extension discorages writing code in this way as it marks the global variable gCache as an undefined reference

I wonder if anyone can comment on this. Is this simply a bug in the Julia Extension? Or is something more significant going on here?

You should probably just do version A. Thr global keyword there is redundant. This will run as a top level statement and will be cached at precompile time.

__init__ can be useful when you need to execute code at runtime initialization. This is for things that are different on each run or depend on external environment variables. In light of static compilation via juliac, use of init is highly discouraged.

If you want to see the difference try to use rand() and make the module a package.

3 Likes

(edit: woops - replied to the wrong post)

You’ve just answered my next question, which I just posted here