An idea for putting imports inside of Julia functions

I’ve often wanted to put imports inside of functions to delay loading potentially slow-to-load packages until I really need them in a given session (a habit from Python, but maybe even more useful in Julia due to latency). The other day I put together this idea which I figured I’d share for feedback or if anyone else finds it useful. Definitely hacky so beware, but the concept is maybe ok I think.

The idea is it lets you write stuff like:

function foo()
    @dynamic import Images
    Images.bilinear_interpolation(rand(10,10), 2.5, 3.7)
end

and Images (as an example here) won’t be loaded until foo is actually called (you still need Images it in your Project.toml). You can put foo in a precompiled package and its fine too.

Note that it wouldn’t work if you simply did @eval import Images because of world-age, which is the main thing this macro works around, by essentially redirecting to an invokelatest(foo) after @eval'ing the import. As a consequence it breaks inference, but that’s to be expected for anything like this.

Code is: An idea for putting imports inside of Julia functions · GitHub

2 Likes

Is it similar to GitHub - JuliaPackaging/Requires.jl: Lazy code loading for Julia?

Slightly different purpose I’d say. With Requires.jl, you can do stuff in response to the user loading a package. With this, you can trigger the package load yourself.

1 Like