iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐤

How to use Julia packages under development in Notebooks

に公開
2023/07/18

https://qiita.com/cometscome_phys/items/989389db3540ebd9e026

The article above is a helpful reference for how to create a Julia package. When creating a package, you may want to proceed with development while checking the behavior and usability on a Jupyter Notebook. While it is not particularly difficult, I will summarize the method here.

How to Call the Package

By running Pkg.activate("path/to/package/folder") in a notebook as shown below, you can load packages under development or local packages using using PackageName. Additionally, by using using Revise, changes made to the package's source code will be applied in real-time (however, Revise.jl must be loaded before loading the package). If you have never used Revise.jl, uncomment Pkg.add("Revise") to install it.

using Pkg
# Pkg.add("Revise")
using Revise
Pkg.activate("path/to/package/folder")
using PackageName

If you created a package with PkgTemplates.jl as described in this article, it should be created in the directory returned by pwd(). If you want to specify the location, move to the desired directory using PowerShell or a similar tool before starting julia. Alternatively, you can load it like this:

include("path/to/package/folder/src/PackageName.jl")
using .PackageName

However, if you generate documentation using Documenter.jl, docs/make.jl contains using PackageName and lacks the ., which will cause an error.

Concrete Example

For example, consider the following source code.

PackageName/src/PackageName.jl
module PackageName

function hello(a)
  println(a)
end

end

In this case, you should be able to call the functions within the package as shown below. (While results will change if you rewrite the package, without using Revise, only the results at the time the package was loaded will be output, and changes to the source code will not be reflected in the results.)

julia> PackageName.hello(123)
123

Omitting the Package Name

If you want to call the function without specifying the package name, use export hello as shown below.

PackageName/src/PackageName.jl
module PackageName

export hello

function hello(a)
  println(a)
end

end

In this case, you can call it with just hello() as shown below.

julia> hello(123)
123

Executing Tests

Tests can be executed as follows.

include("path/to/package/folder/test/runtests.jl")

Discussion