Modules can be loaded in Julia using either the using
statements or the import
statements. While they are often used interchangeably, these statements are different in terms of function extension. In this Answer, we'll discuss the difference between using
and import
statements.
using
statement The using
statement is conventionally used to import a module. When the using
statement is used, the module name is imported in the namespace and the exported variables are available in the global scope.
Note: All code examples in this Answer have been implemented in Julia 1.8.1.
Let's look at the following code example to understand the using
statement better:
# Define a dummy variablemodule foof = 3g = 4export fendusing .fooprintln("f: ", f)println("g: $(foo.g)")
In this code:
Lines 2–6: A module foo
is defined which defines variables f=3
and g=4
and exports f
.
Line 8: The module foo
is loaded in the main scope using the using
statement.
Line 9: f
is loaded as a global variable because of export
in foo
, and its value is printed for verification.
Line 10: Since g
is not exported by foo
, it needs to be used with its module name.
Note: If you try to export a variable of the module that's already declared before the module is loaded, Julia will issue a warning and will stick to the prior declaration.
import
statementWhen a module is loaded using the import
statement, only the module name is loaded in the namespace. All variables and functions need to be loaded using the module name.
We'll use the same example as before, with the key difference of loading the module using the import
statement. Let's look at the following code example to understand the import
statement better:
# Define a dummy variablemodule foof = 3g = 4export fendimport .fooprintln("f: ", foo.f)println("g: $(foo.g)")
In this code:
Lines 2–6: A module foo
is defined which defines variables f=3
and g=4
and exports f
.
Line 8: The module foo
is loaded in the main scope using the import
statement.
Line 9: Even when f
is exported by foo
, it can only be used with the module name.
Line 10: g
is being loaded with its module name.
Apart from the scope of the exported variables, one key difference between the using
statement and the import
statement is that a module method can only be extended using the import
statement. Let's have a look at the following code example:
module randomModulerandomFunction() = "This is a nice function in a nice module."export randomFunctionendusing .randomModule: randomFunctionrandomFunction() = "This is a nice function."println(randomFunction())
Here, trying to extend the randomModule.randomFunction()
using the using
statement causes an error. This can be fixed by using the import
statement.
module randomModulerandomFunction() = "This is a nice function in a nice module."export randomFunctionendimport .randomModule: randomFunctionrandomFunction() = "This is a nice function outside the nice module."println(randomFunction())
Free Resources