Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does include do?

Tags:

julia

As far as I could understand from the documentation and several posts on the web, the statement

include("myfile.jl")

just takes the code in myfile.jl and pastes it on the calling file (or in the console), replacing the line with the include statement.

Please correct me if I am wrong. I am just beginning with Julia. However, I have also seen the following comment by one of Julia's creators:

"include works in the dynamically-current module, not the lexically-current one.
It is really a load-time function, not a run-time one."

What is the difference between dynamically-current and lexically-current?

like image 512
Soldalma Avatar asked Mar 11 '23 08:03

Soldalma


1 Answers

It's not a function call because if myfile.jl is just a = 2 and you do include("myfile.jl"), then you can check in the REPL that a = 2. In functions that a would have been defined in a different scope, and then erased after the function is ended. So this is a clear difference in behavior. Here's an example REPL session demonstrating the difference:

julia> a
ERROR: UndefVarError: a not defined

julia> function incl(file)
           a = "not 2"
           include(file)
           @show Main.a
           @show a
       end
incl (generic function with 1 method)

julia> incl("myfile.jl")
Main.a = 2
a = "not 2"
"not 2"

julia> a
2

This is what they mean by "dynamically-current" vs "lexically-current". Lexically, a function runs in its own scope which is only accessible from within the functions actual code – there is no other way to access or change local variables. include always runs at the current global scope even when called from inside of a function. Julia's eval function behaves similarly – you cannot see or change local variables with eval only global ones.

like image 181
Chris Rackauckas Avatar answered Mar 12 '23 20:03

Chris Rackauckas