Reputation: 18540
Question: What is the difference between using
and import
in Julia when I'm building my own module?
My guess based on reading the docs: using
is used to bring another module into the name-space of the current module. import
is used to bring specific types/functions/variables from other modules into the name-space of the current module.
So, how wrong am I?
Upvotes: 98
Views: 38362
Reputation: 10306
The documentation (updated link for Julia 1.4) about this is excellent. Here's the excerpt which I find to be the most succinct summary:
(a demo module to make the examples below specific)
module MyModule
export x, y
x() = "x"
y() = "y"
p() = "p"
end
(this is a table in the documentation, but StackOverflow still won't add support for tables so... reformatted)
Command
using MyModule
x
and y
) as well as names MyModule.x
, MyModule.y
, and MyModule.p
MyModule.x
, MyModule.y
, and MyModule.p
using MyModule: x, p
x
and p
import MyModule
MyModule.x
, MyModule.y
, and MyModule.p
MyModule.x
, MyModule.y
, and MyModule.p
import MyModule.x, MyModule.p
x
and p
x
and p
import MyModule: x, p
x
and p
x
and p
Upvotes: 72
Reputation: 14695
A summary of the main difference, in a way that I find easy to remember:
using NiceStuff
allows usage access to exported names without the module qualifier, which import NiceStuff
doesn't; andimport NiceStuff: nice
allows extension access (adding methods) to the specified function without the module qualifier, which using NiceStuff: nice
doesn't.And a minor difference:
X as Y
syntax is allowed for individual identifiers with both using
and import
(using Random: randstring as rstr
, import Random: randstring as rstr
) but for the module name itself, import Random as Rnd
is allowed while using Random as Rnd
is an error.
Some other points I found useful from the Modules docs page
using ModuleName
is the only form for which export lists matter at all.
import NiceStuff
is equivalent tousing NiceStuff: NiceStuff
.
Upvotes: 7
Reputation: 2619
The Julia Modules documentation states:
The
import
keyword [...] only operates on a single name at a time. It does not add modules to be searched the wayusing
does.import
also differs fromusing
in that functions must be imported usingimport
to be extended with new methods. [...] Functions whose names are only visible viausing
cannot be extended.
(Emphasis mine.)
For example, you can use import
to add methods to Base.show
to pretty-print your own types, but not with using
.
There is also importall
that imports all exported names of a module.
(This answer refers to Julia 0.6; the documentation was reworded for 1.0.)
Upvotes: 80