Suppose that I would like to access, from inside a module, a type on an englobing scope. To be concrete:
file Englobing.jl
using myModule
type MyType
a::Float64
b::Vector{Float64}
end
t = MyType( 1., [ 1., 2. ] )
x = [ .5, .5 ]
myFunc( x, t )
file myModule.jl
module myModule
export myFunc
function myFunc( x::Vector{Float64}, z::MyType )
[ operations ]
end
end
In this case, I would like to be able to access the type MyType from inside the module myModule, without using global
s.
Option 1:
You can export types too. Eg if Englobing.jl
were a module, you could have:
export MyType
Then, within your myModule.jl
file you could have:
using Englobing
Option 2
If Englobing.jl
weren't a module (which it isn't currently written as), you could just use
include("Englobing.jl")
within MyModule.jl
.
Both of these do depend, however, on not having a situation where Englobing.jl
uses something (function, type, object, etc.) from MyModule.jl
while at the same time MyModule.jl
uses something from Englobing.jl
. If the desired outcome is to have a situation like that possible, I do not believe that is achievable in Julia, though I don't quite see why it would be desirable either.
We try to avoid implicit dependencies, ie saying "give me whatever definition of MyType
might be around". You have to say exactly where it comes from.
However, it is possible for two modules to use each other. module A
can contain using B
, and module B
can contain using A
. You have to order the statements in each so that one can be loaded during loading of the other, but it can work. Of course this is frowned upon, since two modules that depend on each other are not really separate in a meaningful way.
Another solution is to put one module lexically inside the other. It is possible to import variables from scopes that surround the code for the module itself:
module Outer # or just Main, the default
type MyType
...
end
module myModule
import ..MyType # imports from the outer module
end
using .myModule
end
As Michael said, you could then put the code for myModule
in a separate file, and include
it in different places to automatically pick up different definitions of MyType
. However it's preferred to just have a clean dependency tree of modules.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.