What are the essential differences between `include` a file and `using` a module?

What are the essential differences between the following two workflows and what are their respective usage scenarios? Or in another word, what’s the necessity for writing a module instead of a plain .jl file?

  1. Write some functions in a file named myFile.jl:
function sayHello()
    println("Hello, world!")
end

and call them in the REPL by:

include("myFile.jl")
sayHello()
  1. Write some functions into a module in the file myFile.jl:
module myFile
export sayHello
function sayHello()
    println("Hello, world! ")
end
end

and call them in the REPL by:

push!(LOAD_PATH, ".")
using myFile
sayHello()

By the way, must the module name be the same as the file name?

1 Like

If you include a file then you are placing the function name in the global space and the function has access to any variable in the global space.

If you are “using modulename” then the function sayHello is living inside the module name space and has no access to any variables in the global space. The function only has access to variables inside the module space.

4 Likes

When you import a module, your code and module are in different scopes. A variable defined inside the module is inside the scope of the module vice versa, otherwise when including a file it works as if you copy and paste the contents of the file in the place where you call include.

Also, a module has its own dependencies and this can help to avoid errors and isolate parts of the code.

In my personal opinion, for small things that you want to split into different files for organization, but are of the same context and purpose, using files and include is better. For separate pieces with a specific focus, I prefer to use modules, like splitting a website’s backend into three modules: Auth, DB, Services. Each module divided into files.

3 Likes

See my answer here: How to structure project in julia - #44 by Henrique_Becker

2 Likes