Calling Multiple User-defined Julia Functions from Python

After getting the basic PyJulia installation to work, a question I have is regarding importing Julia files. After opening python and creating a Julia object with j = julia.Julia(), I can then use fn = j.include(“file.jl”). However, this allows me to call only one function using fn(“parameters”). However, when the Julia file has more than one function, this approach only allows to me to call the last function defined in the Julia file. Is there a simple way to call each Julia function separately? I’m new to this, so I’m probably missing something simple.

This question a little dated, but since there are no answers and I just went through this, I thought I would share.

I’m new to this, so I’m probably missing something simple.

Simple, yes, but I also found it hard to find a good example of how to do this! I forget where I found the exact example that led me to the code below, although there are various old snippets similar to this if you google long enough.

First, wrap your Julia code in a module:

# filename: MyFuncs.jl
module MyFuncs

function add(x, y)
   return x + y
end

function mult(x, y)
   return x * y
end

end # MyFuncs

Then, assuming pyjulia is set up, you can do

import julia
j = julia.Julia()
j.include("MyFuncs.jl") # load the MyFuncs module
from julia import MyFuncs as my_funcs

print(my_funcs.add(2,3))                 # prints "5"
print(my_funcs.mult("Hello ", "world!")) # prints "Hello world!"  :-)

Hope someone finds this useful!

Cheers,
Kevin

4 Likes