Mikael Fremling
Mikael Fremling

Reputation: 772

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?

Upvotes: 3

Views: 657

Answers (1)

Bill
Bill

Reputation: 6086

The "using" statement runs when the line of code is encountered, and does not have to be at the top of the file. It does need to be in global scope, which means that the variables in the module loaded with "using" will be available to all functions in your program after the "using" statement is executed, not just a single function as might happen in the local scope of a function.

If you call the using statement as an expression within a Julia eval statement, all code executed within the "eval" statement in Julia is automatically done so in global scope, even if the eval is syntactically called within a function's local scope. So if you use the macro @eval

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

this acts as if the using PyPlot is done outside a function, and so avoids the syntax error.

Upvotes: 3

Related Questions