Let’s say I have a file called test_module.jl
and inside that I have defined a structure that I would like to use in other julia scripts.
module myModule
export myStruct
struct myStruct
param1::Integer
param2::Integer
end
end
In another file test_include.jl
, I would like to access and use the myStruct
structure. My intuition here (along with this SO question and Julia’s Module docs) would suggest that the below code should work. However, line 2 throws and error because the imported module has been imported as Main.myModule
.
include("test_module.jl")
m = myStruct(1,2) > UndefVarError: myStruct not defined
Making either of the next changes results in expected behavior.
Option 1:
include("test_module.jl")
m = Main.myModule.myStruct(1,2)
Option 2:
include("test_module.jl")
using Main.myModule
m = myStruct(1,2)
My Questions
- Am I importing the module correctly and do I have my module setup correctly? Everything that I’ve looked at suggests that I do.
- Why does
include(julia_file)
result in modules from that file being included in the Main namespace? Is there a way to change/control that?
- What can I change in either file so that when I include the file, I have direct access to
myStruct
?
1 Like
There should be no need to prefix by Main.
.
So you can do myModule.myStruct(1,2)
or
julia> using .myModule
julia> myStruct
myStruct
- Yes, looks fine.
- Because you are calling the
include
from Main (which is the “default” module).
- One of the points of having a
module
is to namespace the symbols in there. You could just remove the module
completely if you want everything to happen in the same namespace as where you include it.
2 Likes
Thanks for the reply @kristoffer.carlsson. I tried both of your suggestions though, but neither of them worked.
Suggestion 1:
include("test_module.jl")
m = myModule.myStruct(1,2) > UndefVarError: myModule not defined
Suggestion 2:
include("test_module.jl")
using .myModule > UndefVarError: myModule not defined
m = myStruct(1,2)
Did I understand your suggestions correctly?
I tried your answer to question 3 and that worked, which is good to know. I’d still like to figure out what’s going on with module imports though.
shell> cat mymod.jl
module myModule
export myStruct
struct myStruct
param1::Integer
param2::Integer
end
end
julia> include("mymod.jl")
Main.myModule
julia> myModule.myStruct(1,2)
Main.myModule.myStruct(1, 2)
julia> using .myModule
julia> m = myStruct(1,2)
myStruct(1, 2)
4 Likes
Wow, really sorry about that. I’m not sure why I got those errors initially. I’ve retried your suggestions and they all work. Thanks for the help!