Setting a module global from another module

I have two packages , lets call them pkgA and pkgB .
The sources of the two packages are shown below .

module pkgA
const glob = [1,2]
greet() = print("Hello World!")

end # module
module pkgB
import pkgA
println("SETTING pkgA.glob[1]")
pkgA.glob[1] = 1000
@show pkgA.glob
greet() = print("Hello World!")
end # module

now when i run using pkgB , the @show shows the correct value of
the global from pkgA. However after that if i use pkgB.pkgA.glob it shows
the original value that was definined in pkgA.

└── julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.7.2 (2022-02-06)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> using pkgB
[ Info: Precompiling pkgB [e2401a67-4941-42e4-a2ee-a5efd2c3b0d6]
┌ Warning: Package pkgB does not have pkgA in its dependencies:
│ - If you have pkgB checked out for development and have
│   added pkgA as a dependency but haven't updated your primary
│   environment's manifest file, try `Pkg.resolve()`.
│ - Otherwise you may need to report an issue with pkgB
└ Loading pkgA into pkgB from project dependency, future warnings for pkgB are suppressed.
SETTING pkgA.glob[1]
pkgA.glob = [1000, 2]

julia> pkgB.pkgA.glob
2-element Vector{Int64}:
 1
 2

we see that pkgB.pkgA.glob is still [ 1, 2] even though in pkgB’s source the first element was set to 1000.

Is this a bug ? This works as expected if the two modules were in the same file and just include(file.jl) but not when they are installed as packages .

This looks like exactly the kind of operation that must occur at initialization time, as discussed in Modules · The Julia Language .

In particular, it mentions:

Depending on compile-time side-effects persisting through load-time. Example include: modifying arrays or other variables in other Julia modules…

Basically, you’re modifying that global during the precompilation process, but the resulting precompiled module doesn’t know that it’s supposed to modify that value every time PkgB is loaded.

You should get the expected behavior if you move that assignment into the __init__() function.

2 Likes