Issue with include

I am seeing an odd issue with how include works. I am using Julia 1.0.2. Here is the simplest case that seems to cause issues:


function f1()
    println("In f1()")
    println("In f1(), jz=",jz)

function f2()
    println("In f2()")
    println("In f2(), jz=",jz)
    jz = 0
    println("In f2(), after reset, jz=",jz)


println("Including parameters")
jz = 1
println("In params.jl, jz=",jz)

Output from running julia_include_issue.jl

In f1()
Including parameters
In params.jl, jz=1
In f1(), jz=1
In f2()
Including parameters
In params.jl, jz=1
ERROR: LoadError: UndefVarError: jz not defined [this happens at the line in f2() where it tries to print jz]

Any thoughts on what I’m doing wrong?

You shouldn’t use include from inside functions.


Is there a better way to do it if I want to run code from within a function (essentially just replacing the include statement with the text of the file and evaluating)?

What is in params.jl? That will help.

If the content of the file is changing and you want to observe that with multiple run of the function. No you can’t. That’s impossible. You need to find a different way to solve your actual problem. For example, if the things to be included is just some parameters, as the name suggested, you should just pass those in as values and you can find you favorate data storage format to load it from disk.

If the content is basically fixed and this is just a way to reuse the code, then that’s what macros for and you should use that instead. (write a macro that expands to the code you want to include). Or better, use a function if you can.