Tip: macro to install/use package in temporary environment

Julia automatically installs a package when you try to load it:

julia> using Plots
 │ Package Plots not found, but a package named Plots is available from a registry. 
 │ Install package?
 │   (@v1.9) pkg> add Plots 
 └ Select environment:
 > 1: `/tmp/jl_Y5S4mT` (/tmp/jl_Y5S4mT)
   2: `~/.julia/environments/v1.9/Project.toml` (@v#.#)
   Resolving package versions...
<...>
julia> # Plots is loaded

so there’s probably not much to be gained by such a macro. By default, it only asks to install the package into the global or current env, in order to get the temp env automatically you need to add this to startup.jl:

insert!(LOAD_PATH, 2, mktempdir())

Also, relatively recently there appeared an idea of “auto-loading” a package when something from it is used in the REPL. Combining these two features (auto-load and auto-install) makes working in the REPL even more convenient:

# fresh Julia start
julia> SVector(1, 2)
[ Info: Loading StaticArrays for SVector ...
 │ Package StaticArrays not found, but a package named StaticArrays is available from a registry. 
 │ Install package?
 │   (@v1.9) pkg> add StaticArrays 
 └ Select environment:
 > 1: `/tmp/jl_Xo2l9A` (/tmp/jl_Xo2l9A)
   2: `~/.julia/environments/v1.9/Project.toml` (@v#.#)
   Resolving package versions...
<...>
2-element SVector{2, Int64} with indices SOneTo(2):
 1
 2

See my take on the startup.jl with auto-load and auto-install at startup.jl · GitHub. There are others as well.

4 Likes