Using vs include

include("./basis.jl")
include("./ham.jl")
#using basis
#using ham

This is the header of a julia script. In the same directory, there are two files basis.jl and ham.jl.

To include is just to copy and paste the content of the files in the current script, right?

I find that if the include is commented out, while the using is uncommented, I get an error

ERROR: ArgumentError: Package basis not found in current path.

ps. the other files contain only functions, no module definition

2 Likes

Assuming that the files contain a module with the same name (i.e. module basis ... end), then you need to do using .basis.

using with no period looks at the environment for installed packaged. The leading period indicates that you are referring to a module defined in the current module.

If you do not have a module with a matching name to the file, then it doesn’t work because copy and pasting the contents of the file does not create a module with a matching name.

6 Likes

No, it’s not. In most cases it behaves like that, but it’s not what it does. Instead, as the documentation says:

Base.include([mapexpr::Function,] m::Module, path::AbstractString)

Evaluate the contents of the input source file in the global scope of module m

with the special case that include(file) uses the current module for m. So it’s more like “copy and paste the content of the file at the top of the module”. It’s the reason you can’t just include a file inside a function, which would work if it was literally just copying in the code.

5 Likes

It’s common for beginners or people unfamiliar with modules to confuse import/using and include or wonder why there’s 2 things for code loading. include evaluates source code from a file, while the primary purpose of import/using is to share names between 2 modules. Imports only load (often cached and precompiled) code from packages directly and extensions indirectly, which are organized into modules. Imports and include are really 2 independent actions.

I may not have to say this, but another common tip is to avoid multiple includes of a module-defining source file because it would create multiple independent runtime copies of the module, which is almost always unintended and buggy. As you can probably tell from the good information in the thread, you would include the file once to load the module, then many other modules can each import/using names from that one module. Of course, if the module was a package, then you wouldn’t need to include at all, and the code loading only occurs on the first import.

3 Likes

See also : 11 - Developing Julia packages - Julia language: a concise tutorial

2 Likes