A python "as" equivalent in julia

Viewed 362

When I want to import a package in python, I can alias it:

import package_with_a_very_long_nameeeeee as pl

After that statement, I can refer to the package by it alias:

pl.foo()

julia allows me to do:

using PackageWithAVeryLongName
pl = PackageWithAVeryLongName
pl.foo()

But it feels like an ugly hack, possibly with implications I do not understand.

Is there an idiomatic way to alias imported packages in julia?

2 Answers

This is now possible on the upcoming Julia 1.6 using the exact same syntax as Python uses:

julia> import LinearAlgebra as LA

julia> typeof(LA)
Module

help?> LA.svd
  svd(A; full::Bool = false, alg::Algorithm = default_svd_alg(A)) -> SVD

On prior versions, you can do what @Bill suggests — but I'd strongly recommend doing so as a const assignment alongside an import:

julia> import SparseArrays

julia> const SA = SparseArrays
SparseArrays

python:

>>> import matplotlib as plt
>>> type(plt)
<class 'module'>
>>>

julia:

julia> using Plots
[ Info: Precompiling Plots [91a5bcdd-55d7-5caf-9e0b-520d859cae80]
julia> const plt = Plots
Plots
julia> typeof(plt)
Module

So, it is pretty much the identical effect between languages. What may make this usage less than ideal, thus seem ugly in Julia is that multiple dispatch usually allows the export of function names from multiple modules without a conflict since their arguments usually differ. So having to precede the function name with a module alias might mean that something needed export and was not exported with the module. The exceptions ought to be rare.

Related