How to create packages for Julia

A package is a collection of functions or modules created for a specific functionality or use. In Julia, packages have a .jl extension.

In this article, we’ll learn how to create a package in Julia.

How to create a package in Julia

There are two ways to create a package in Julia:

  1. Using generate and pkg.
  2. Using PkgTemplates.

Using generate and pkg

The generate command is a minimal functionality used to quickly and easily create a package while the command line is on package manager or pkg mode.

On Julia’s command line:

  • Type ] on Julia to exit julia> mode and enter package manager or pkg mode.

  • Type generate Mypackage. This generates a package with the name Mypackage, with two files: src, where code is stored, and project.toml, where general information like the author and Julia version about the package is stored.

  • Press backspace to exit pkg mode and enter julia> mode. This will help us specify the package contents. Specify the contents of the package. For example, Mypackage will contain a name function that prints out the package name whenever it is called.

module Mypackage
name() = println("this package is called Mypackage")
end

  • Type ] to go back to package manager mode. This will help us activate the new package.
activate .
  • While in Julia mode, use Pkg to add the package and call the name() function. This prints out the package name as earlier specified.
import Pkg
Pkg.add("Mypackage")
Mypackage.name()

Output

this package is called Mypackage

Using PkgTemplates

The PkgTemplates is a library that helps create a package easily either on the command line or in a jupyter notebook.

This is the recommended method because it comes with functionalities that help you meet Julia’s package creation, testing, documentation, and publishing standards.

import Pkg
using Pkg
Pkg.add("PkgTemplates")

First, use the Template module to specify the package’s user and other plugins that will help you store and document your package on Github.

using PkgTemplates
t = Template(;
    user="your-GitHub-username",
    authors=["your-name"],
    plugins=[Git(name = "your-GitHub-username", email = "your-github-email"),GitHubActions()
           ],
       )

This automatically creates the standard project/package structure for Julia.

Then give your package a name. In this case, we named it Mypackage.

t("Mypackage")

Lastly, specify the package functionality by adding functions and navigating to the Julia command line to activate the package as demonstrated earlier.

module Mypackage
name() = println("this package is called mypackage")
end

Note: The standard naming convention for a package in Julia is either CamelCase as in MyPackage.jl or Title Case as in Mypackage.jl.

Use the terminal below to run the code above. Simply type julia to start:

Terminal 1
Terminal
Loading...
Copyright ©2024 Educative, Inc. All rights reserved