Does Julia allow subpackages?

Is it possible to define a module A and a submodule B without including B code in A directly or via an include() call? The goal is for “import A” not to load A.B and require users to explicitly “import A.B”.

1 Like

Well, if you don’t export B from the A module you need to explicitly import A.B to use the B module:

julia> module A
       module B
       export foo
       foo() = 42
       end
       end
A

julia> import A

julia> B.foo() # errors cause we have not imported A.B
ERROR: UndefVarError: B not defined

julia> import A.B

julia> B.foo()
42

This is not quite what I want. I want to have module B code in a separate file which would only be loaded when I do import A.B, but not when I do import A. This is how modules defined inside a package behave in Python.

See my latest post in https://github.com/JuliaLang/julia/issues/4600 for a plan to implement what I think you’re asking about.

@StefanKarpinski - your post seems to be about relative imports. What I am looking for is a much simpler scheme. I expected that import A.B would first include("src/A.jl/A.jl"). If doing that creates A.B module, we are done. If not, look at src/A.jl/B.jl. If that is a file - do include("src/A.jl/B.jl") in the module A context. If it is a directory, do the same with src/A.jl/B.jl/B.jl.

The proposal that I was referring to (“my latest post”) addresses exactly that. It works for relative or absolute imports as long they are for not-yet-defined submodules of some module that you are currently loading, which seems to be just what you’re asking about.