Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly load a module in Julia?

I've been reading a lot of Julia documentation (version 0.4) and am still having problems with loading Julia files. This seems like it should be really easy. So, plainly and simply, how are we supposed to use Julia code from other files directly in our current code? And, as a related, helpful bonus, is there any history or language design decisions that, understood, would illuminate the situation?

P.S. I'm using 0.4.


If you want problem specifics, here are some things I'm dealing with:

First

Using the REPL, I want to use some functions I have written in a different file. Supposedly, I should be able to load said file like this:

julia> using Foobar

That just gives me ArgumentErrors no matter what I do. I've tried including it before trying to use it:

julia> include("Foobar.jl")
julia> using Foobar

I've also tried updating the load path before trying to use it:

julia> push!(LOAD_PATH, "/Users/me/julia")
julia> using Foobar

Second

When I try to fix the first problem by including the file before using it, I get an error for any line that has: using .... The message is that a module cannot be found in path. Or in other words, I'm trying to load a module in the current working directory that depends on another module in the current working directory. When I include the file I'm trying to load, it tries to find the dependency and cannot.

Third

I've tried relative paths. I.e. I'm in the same directory as the .jl file and do:

julia> using .Foobar
like image 453
Joe Hansen Avatar asked Mar 13 '23 00:03

Joe Hansen


2 Answers

if you use include("/path/to/myscript.jl") then you should then have access to any functions, objects, etc. defined in the file you called with include(). No additional calls to using should be needed.

Here is an answer that gives more info on details for creating whole packages (rather than just individual scripts like in the example above), how to do them, and how the using terminology factors in with them: julia: create and use a local package without Internet . For instance, packages must be installed in a particular path relative to your other julia files, not just in the arbitrary working directory that your script is in.

See also here for a longer tutorial on packages.

like image 199
Michael Ohlrogge Avatar answered Mar 19 '23 01:03

Michael Ohlrogge


It seems to work well enough here:

julia> push!(LOAD_PATH, "/Users/me/julia")
2-element Array{ByteString,1}:
 "/Applications/Julia-0.4.5.app/Contents/Resources/julia/local/share/julia/site/v0.4"
 "/Users/me/julia"

julia> readdir(LOAD_PATH[end])
1-element Array{ByteString,1}:
 "MyModule.jl"

julia> using MyModule

julia> x
"Hi there"

where MyModule.jl contains:

module MyModule
  export x
  x = "Hi there"
end
like image 26
daycaster Avatar answered Mar 19 '23 02:03

daycaster