首页 > 解决方案 > Load Julia modules on demand

问题描述

I I have a very simple question. Is it possible to load modules on demand in Julia. That is, can the modules be loaded when they are actually needed instead of being loaded at "parse-time" at the top level.

The use case scenario I have in mind is that I have some set of code that is able to do some plotting using PyPlot, but code is far from always executed.

At the moment this means that I have at top level a statement like using PyPlot, which takes quite a load of time to load.

(Yes i know: One should not restart Julia to often, bla bla bla... but nevertheless this is a point of annoyance)

Is there a way to ensure that PyPlot is only loaded is if is actually needed? The simplest idea would have been to include the using PyPlot inside the function that actually do the plotting

function my_plot()
    using PyPlot
    plot(1:10,1:10)
end

but this results in a syntax error:

ERROR: syntax: "using" expression not at top level

So, is there another way to achieve this?

标签: matplotlibjulia

解决方案


“using”语句在遇到代码行时运行,并且不必位于文件顶部。它确实需要在全局范围内,这意味着加载“using”的模块中的变量将在“using”语句执行后可供程序中的所有函数使用,而不仅仅是在函数的局部作用域。

如果您将 using 语句作为 Julia eval 语句中的表达式调用,则在 Julia 中的“eval”语句中执行的所有代码都会在全局范围内自动执行,即使 eval 在函数的本地范围内按语法调用也是如此。所以如果你使用宏@eval

function my_plot()
    @eval using PyPlot  # or without the macro, as eval(:(using PyPlot))
    plot(1:10,1:10)
end

这就像使用 PyPlot 在函数外部完成一样,因此避免了语法错误。


推荐阅读