How to import a custom module in Julia

Modules are used to organize the code that can be maintained and reused more easily. We can encapsulate the related code into a module and enhance the visibility of the code.

Create a module

Let’s create a module in Julia.

The module keyword

We use the module keyword followed by the name of the module.

module MyModule

The export keyword

After declaring the module, we use the export keyword followed by the function names that should be visible where we import this module.

module MyModule

export sum_function

The sum_function() function

This function accepts two variables, a and b, and returns their sum.

function sum_function(a, b)
    return a + b
end

Use a module

There are two ways to use a created module in another piece of code.

The using keyword

We use the using keyword to import the entire module and all its exported variables and functions.

using MyModule

Let’s run the following code to understand the working of the using module:

main.jl
mymodule.jl
module MyModule
export sum_function
function sum_function(a, b)
return a + b
end
end # end of module definition

Explanation

  • Line 1: We use the include() function to include the mymodule.jl file in the current namespace.
  • Line 2: We use the using keyword to completely import the MyModule module.
  • Line 4: We call the sum_function() function with arguments 2 and 3 and store the result in a variable result.
  • Line 6: We prints the value of the result variable to the console.

The import keyword

We use the import keyword to import the specific module and make the specified functions or variables available. It is useful when we require a small subset of the functionality provided by a module.

import MyModule.sum_function

Let’s run the following code to understand the working of the import module:

main.jl
mymodule.jl
include("mymodule.jl")
import MyModule.sum_function
result = sum_function(2, 3)
print(result)

Explanation

  • Line 1: We use the include() function to include the file mymodule.jl in the current namespace.
  • Line 2: We use the import keyword to selectively import the sum_function() function from the MyModule module.
  • Line 4: We call the sum_function() function with arguments 2 and 3 and store the result in a variable result.
  • Line 6: We print the value of the result variable to the console.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved