What is the difference between `using` and `import` in Julia when building a module?
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.)
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
- in-scope: All exported names (
x
andy
),MyModule.x
,MyModule.y
, andMyModule.p
- extensible:
MyModule.x
,MyModule.y
, andMyModule.p
- in-scope: All exported names (
using MyModule: x, p
- in-scope:
x
andp
- extensible: (nothing)
- in-scope:
import MyModule
- in-scope:
MyModule.x
,MyModule.y
, andMyModule.p
- extensible:
MyModule.x
,MyModule.y
, andMyModule.p
- in-scope:
import MyModule.x, MyModule.p
- in-scope:
x
andp
- extensible:
x
andp
- in-scope:
import MyModule: x, p
- in-scope:
x
andp
- extensible:
x
andp
- in-scope: