How to share a module between several modules


Sorry for the noob question. I have a utility module that I would like to share between two other modules. As far as I understand, simply using include("whatever/path/UtilityModule.jl") followed by using .UtilityModule inside each module will just duplicate the code of the utility module instead of “sharing” it. What is the proper way for doing this apart from creating a package (in this case, the module is not worth putting into a separate package)?
I would appreciate any help on this issue.

The module FinEtools.jl/FEMMBaseModule.jl at main · PetrKryslUCSD/FinEtools.jl · GitHub
(and others) use functions from
FinEtools.jl/MatrixUtilityModule.jl at main · PetrKryslUCSD/FinEtools.jl · GitHub
These two modules stand side-by-side, created by inclusion from
FinEtools.jl/FinEtools.jl at 0d9e71744bf3740a67fc16cf89e84f5c50a14bd7 · PetrKryslUCSD/FinEtools.jl · GitHub, the top-level module of the FinEtools.jl package.

1 Like

Thank you!
That’s interesting. I was not aware of ..import syntax I presume it works with using as well. I am still curious if there is a way to use a module from a “general” path.

if there is a way to use a module from a “general” path

By this, do you mean using your own module across disparate projects? If so, your best bet would probably be to build your module as a package, then import it into the specific project that you’re working on.

1 Like

I rather had in mind the situation where the source files for the modules are not in the same folder.

Modules are not associated with folders. The source files can reside anywhere at all.

1 Like

Hi, could you explain why I get ERROR: LoadError: UndefVarError for my module import when I try to use import/using in the same way as you suggested?

What is the structure of your code?

src --------> MyModule.jl
         ---> MyUtilityModule.jl

and inside MyModule.jl I have:

module MyModule
using ..MyUtilityModule

Ok, I think I got it. Modules · The Julia Language
I have to have a separate module that contains both of my modules. Julia namespace approach is quite confusing.

No, I don’t think that is necessary. This should work:
In mysrc.jl

using .MyModule
a = rand(3)
b = rand(3)

using LinearAlgebra
dot(a, b) == MyModule.f(a, b)


module MyModule
using ..MyUtilityModule
f(x, y) = MyUtilityModule.mydot(x, y)


module MyUtilityModule
using LinearAlgebra
mydot(x, y) = dot(x, y)
1 Like

but isn’t this equivalent to implicitly putting two modules into the Main module?