I need to be able to programmatically define a new global variable in a module. Till Julia v1.11 I was able to do this as
function define_global()
m = Module(:MyModule)
Core.eval(m, :(global data))
setglobal!(m, :data, 123)
m
end
This, however, does not work anymore and raises an error:
julia> define_global()
ERROR: Global MyModule.data does not exist and cannot be assigned.
Note: Julia 1.9 and 1.10 inadvertently omitted this error check (#56933).
Hint: Declare it using `global data` inside `MyModule` before attempting assignment.
Stacktrace:
[1] define_global()
@ Main ./REPL[7]:4
[2] top-level scope
@ REPL[8]:1
This, presumably, is a consequence of the new world-age mechanism. In fact, the code below with invokelatest solves the problem:
function define_global(name)
m = Module(:MyModule)
Core.eval(m, :(global data))
invokelatest(setglobal!, m, :data, 123)
m
end
Is there are nicer and cleaner way of doing what I am trying to do?