NOTE: 请参考用户1712368的(Jameson Nash,Julia dev)回答,这个discussion在julia-users邮件列表和Julia manual的这个条目中,要知道为什么这是 not 正确答案 .
这是使用Julia版本0.3.4的多重导入表达式的样子:
julia> parse("import Foo, Bar")
:($(Expr(:toplevel, :($(Expr(:import, :Foo))), :($(Expr(:import, :Bar))))))
julia> dump(ans)
Expr
head: Symbol toplevel
args: Array(Any,(2,))
1: Expr
head: Symbol import
args: Array(Any,(1,))
1: Symbol Foo
typ: Any
2: Expr
head: Symbol import
args: Array(Any,(1,))
1: Symbol Bar
typ: Any
typ: Any
这是一个以编程方式执行此操作的宏,它需要 modules 参数,该参数可以是 :call 或 :vcat Expr 或 Symbol ,必须评估为 Vector{Symbol} :
julia> macro dynamic_import(modules)
(modules = eval(modules))::Vector{Symbol}
ex = Expr(:toplevel)
for m in modules
push!(ex.args, Expr(:import, m))
end
return ex
end
你也可以概括这一行:
module_files = filter(r"^mod[0-9][0-9].jl$", readdir())
通过将其抽象为一个函数,该函数将 Regex 和 String 目录路径作为参数并返回 Vector{Symbol} :
julia> function needed_modules(rx::Regex, dir::String=".")
module_files = filter(rx, readdir(dir))
module_syms = map(m -> symbol(split(m, '.')[1]), module_files)
end
needed_modules (generic function with 2 methods)
所以你可以像这样使用它:
julia> @dynamic_import [:Mod01, :Mod02] # :vcat expression
julia> rx = r"^Mod[0-9][0-9].jl$";
julia> @dynamic_import needed_modules(rx) # :call expression
julia> modules = needed_modules(rx)
2-element Array{Symbol,1}:
:Mod01
:Mod02
julia> @dynamic_import modules # Symbol
最后,您可以将它全部包装到模块中,以便您可以使用DynamicImport:
Note: 当前我尝试从模块运行相同的示例时得到这个:
julia> using DynamicImport
julia> @dynamic_import [:mod01, :mod02]
julia> rx = r"^mod[0-9][0-9].jl$";
julia> @dynamic_import needed_modules(rx)
ERROR: rx not defined
julia> modules = needed_modules(rx)
2-element Array{Symbol,1}:
:mod01
:mod02
julia> @dynamic_import modules
ERROR: modules not defined
但它工作正常如果我在REPL中定义对象,我想这是一个涉及卫生的问题,这是我没有经历过的事情,所以我会在julia-users邮件列表中询问 .