How to load a file-as-a-module when an Environment is present

I need to load a module defined in a local file without using includet() (because of an issue with nested includet).

I tried then LOAD_PATH and at the beginning this works:

a.jl :

using Pkg
Pkg.activate(@__DIR__)
push!(LOAD_PATH,@__DIR__)
using Foo
foo(1)

Foo.jl:

module Foo
export foo
foo(x) = x + 1
end

However, as soon as the environment where the file a.jl resides is defined (i.e. has a Project/Manifest.toml) the using Foo line returns the error that Foo is not found. For example, adding the CSV package to force the creation of an environment:

a.jl :

using Pkg
Pkg.activate(@__DIR__)
Pkg.add("CSV")
push!(LOAD_PATH,@__DIR__)
using Foo #`ERROR: ArgumentError: Package Foo not found in current path.`
foo(1)

How can I load Foo.jl ?

Do you need a.jl and Foo.jl to live in the same directory?

If not, you could create a specific directory for Foo.jl:

project/
β”œβ”€β”€ Project.toml
β”œβ”€β”€ a.jl
└── lib/
    └── Foo.jl

and then a.jl could push!(LOAD_PATH, joinpath(@__DIR__, "lib")) so that I think your trick would continue working.


But better yet, if you don’t have strong constraints on the file organization, you could give Foo.jl a real package structure:

project/
β”œβ”€β”€ Project.toml
β”œβ”€β”€ a.jl
└── Foo/
    β”œβ”€β”€ Project.toml
    └── src/
        └── Foo.jl

In this case, you’ll be able to Pkg.develop(path=joinpath(@__DIR__, "Foo")) in the top-level project, and everything would work without having to tamper with LOAD_PATH.

1 Like

Oh I see. The env is looked up in the folder of the β€œimported” file.
Solution 1 seems to work for me, even if in my application Foo.jl shares the environment with a.jl, and so I had to trickle a bit:

lib/Foo.jl :

module Foo
using Pkg
Pkg.activate(joinpath(@__DIR__,".."))
export foo
using CSV # or whatever pkg I need (defined in the a.jl folder env)
foo(x) = x + 1 
end

The solution of converting Foo.jl in a full package is a bit too complicate for the people I am working with (e.g. two separate environments)… I feel like Julia somehow push to use Packages when this would not be always needed…