Scope of submodules

Say I have a module A, in which I define a constant. I would like to be able to use that constant in submodules of that module:

module A
a = 2
module B
f(x) = x*a
end
module C
g(x) = x*a
end
end

This does not work:

A.B.f(3)
UndefVarError: a not defined

Clearly, I need to import a into each submodule, but that seems a bit annoying… Would there be a way to automatically inherit from the superscope, possibly with a submodule keyword?

1 Like

There isn’t a way (as far as I know) to automatically inherit from the outer scope, but you might find some of the answers from here helpful: Avoid repeating the same `using` line for enclosed modules

Try import ..a, which however doesn’t free you from importing in general; see also Global Scope in the manual:

julia> module A
           a = 2
           module B
               import ..a
               f(x) = x*a
           end
           module C
               import ..a
               g(x) = x+a
           end
       end
       println(A.B.f(3)) # = 6
       println(A.C.g(4)) # = 6
       eval(A, :(a = 5))
       println(A.B.f(3)) # = 15
       println(A.C.g(4)) # = 9
6
6
15
9

or alternatively using A: a instead of import.

You could also export a, then simply using A:

julia> module A
           export a
           a = 2
           module B
               using A
               f(x) = x*a
           end
           module C
               using A
               g(x) = x+a
           end
       end

Or, if you have a large number of variables to import and prefer explicitly naming the ones to import, then a simple trick would be to put that using/import statement in another file and include that file at the respective positions.
That all at least reduces the problem to a one-liner per submodule. Using some other macro or keyword probably isn’t much less typing.

1 Like