variablespackagejuliausing

How to use "using variable" in Julia


I am trying figure out if it is possible to use package name not explicitly as eg DataFrames etc or as a String variable with a name of this module with using. My test code is:

dependencies=["CSV", "DataFrames", "Plots"]
for pkg in dependencies
    if !haskey(installed_packages, pkg)
        Pkg.add(pkg)
    end
    print(pkg)

   using .pkg
    
end

It breaks on using .pkg (also tryid without a dot, with error TypeError: in using, expected Symbol, got a value of type Core.SlotNumber


Solution

  • Because what you want to do is syntactic (changing how the item after using is interpreted), you'll want the @eval macro:

    @eval using $(Symbol(pkg))
    

    You can check that this has the same syntactical representation as the regular version of using, which proves it's correct:

    let pkg = "Plots"
        @assert :(using Plots) == :(using $(Symbol(pkg)))
    end