Submodules accessing global variables in Parent module

How can we make a submodule access a variable defined in its parent module?
Sorry if this is a really basic question, but I’ve spent almost an hour looking for an answer without any success. I have only seen how to access variables from other child modules at the same hierarchical level, or just unrelated modules. Accessing stuff defined in the parent module would seem to be the most natural one of the “inheritances”, so this is a bit counter intuitive to me. I’m thinking it akin to a “closure”, I guess:

module Parent
const a = 10

module Child
main() = println(a)
end

end

on the REPL:

julia> Parent.Child.main()
ERROR: UndefVarError: a not defined
Stacktrace:
 [1] main()
   @ Main.Parent.Child ./REPL[42]:6
 [2] top-level scope
   @ REPL[43]:1

The use case in question:
I’m working on some complex code that reads and writes across different files on many directories. I have defined a TOML configuration file that stores the directories to use. At the moment I can make it work if I always parse the config file inside every child module, but I would rather do it once in the parent module and make it so that everything is neat and organized for the child modules.

julia> module Parent
       const a = 10

       module Child
       import ..Parent: a
       main() = println(a)
       end

       end
Main.Parent

julia> using .Parent

julia> Parent.Child.main()
10


3 Likes

WR for solution?
Thanks!

2 Likes

As an afterthought:
This implies that we are looking in the parent directory of the “Parent” module, right? This doesn’t seem very different from just making a “brother module” on the same level as “Child” and then reading the variable from there:

module Parent

module Brother
const a = 10
end

module Child
import .Brother: a
main() = println(a)
end

end

Or even then just a completely unrelated module on the same level of “Parent” and accessing it as

module Unrelated
const a = 10
end


module Parent

module Child
import ..Unrelated: a
main() = println(a)
end

end

Is there any merit for one of these approaches over the others?

Julia code generally don’t have many submodules, because they are not needed to avoid most name clashes that occur in OO languages. So the answer is that none of these patterns is very idiomatic in Julia.