How to load a custom Julia package in Python using Python's juliacall
Asked Answered
P

1

11

I already know How to import Julia packages into Python.

However, now I have created my own simple Julia package with the following command: using Pkg;Pkg.generate("MyPack");Pkg.activate("MyPack");Pkg.add("StatsBase") where the file MyPack/src/MyPack.jl has the following contents:

module MyPack
using StatsBase

function f1(x, y)
   return 3x + y
end
g(x) = StatsBase.std(x)

export f1

end

Now I would like to load this Julia package in Python via juliacall and call f1 and g functions. I have already run pip3 install juliacall from command line. How do I call the above functions from Python?

Polis answered 27/12, 2022 at 15:3 Comment(0)
P
9

You need to run the following code to load the MyPack package from Python via juliacall

from juliacall import Main as jl
from juliacall import Pkg as jlPkg

jlPkg.activate("MyPack")  # relative path to the folder where `MyPack/Project.toml` should be used here 

jl.seval("using MyPack")

Now you can use the function (note that calls to non exported functions require package name):

>>> jl.f1(4,7)
19

>>> jl.f1([4,5,6],[7,8,9]).to_numpy()
array([19, 23, 27], dtype=object)

>>> jl.MyPack.g(numpy.arange(0,3))
1.0

Note another option for calling Julia from Python that seems to be more difficult to configure as of today is the pip install julia package which is described here: I have a high-performant function written in Julia, how can I use it from Python?

Polis answered 27/12, 2022 at 15:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.