I think you should get the same error within the defining module if you haven’t assigned a value to it yet (like regularly trying to access the varable).
To avoid this, you check with @isdefined first or assign a sentinel value initially.
I think a const Ref is probably the way you want to go if you cannot initialize the global for some reason. With a Ref you can at least have an #undef.
I’m a little confused: what would you do after you’ve imported the undefined global? The only thing you could theoretically do is assign to it. But Julia doesn’t let you do that, either:
julia> module M
global var = 1
export var
end
Main.M
julia> using .M: var
julia> var = 2
ERROR: cannot assign a value to imported variable Main.var
You’ve gotta explicitly fully-qualify the thing:
julia> M.var = 2
2
And at that point, it also works if it’s not defined!
julia> module M2
global var2
export var2
end
Main.M2
julia> using .M2
julia> var2
ERROR: UndefVarError: `var2` not defined
julia> M2.var2 = 3
3
julia> var2
3
I believe the idea here is that the imported variable is used inside functions, which will only be called once the variable is assigned a value.
As you’ve pointed out, one solution would be to not import the variable, and use the module-qualified name for it in the function. A Ref is another viable option here.
The best one is probably to restructure things so that this isn’t necessary. It’s usually possible to do that.
While often you don’t need to initialize variables on runtime, often you do need to do so.
In my case, which also answers your question @mkitti, I am using a global Configurations.jl @option struct to gather all my variables. Concretely there are some secrets which I need to initialize. I don’t want to write the secrets into the code, so this a classical example where you need runtime initialization of the concrete Configuration object.
Thank you for the workarounds! It is good to know that referencing it via the module name actually works.
For my intuition it is a bug that referencing it directly does not work.
Does someone know about Julia’s variable importing system whether this should work?
After all this discussion I still don’t understand what it is you’re trying to do, why do you want a global variable, and why are the suggested solutions not good enough for you. Please provide a minimal working example, then we can help you improve it.
BTW, yet another potential solution to look into could be ScopedValues.
I guess my wish is to somehow get rid of the brackets [] which I need to use when using Ref. My current workaround is to define a custom RefType which actually forwards dot access. It is just because the typed unitialized global variable look like they can do exactly this, but they don’t do it yet. Hence my mind thinks again and again “come on, this workaround shouldn’t be needed as we have such globals”.