Why doesn't this "include-guard-ish" code evaluate in the correct order?

bertulli
Tue, 17 Jan 2023 18:29:33 +0000
New to Julia

Hi all!

So I was trying to implement a mechanism similar to a very simple C-like include guard:

# file my_script.jl
if @isdefined my_script_provided
    print( "my_script.jl already loaded")
else
    # my code here
    my_script_provided = true
    print("Done!")
end

In such script I load some packages (via usings) and some data in some DataFrames. Point is, I have this include dependency:

data_analysis.jl ---------> constants.jl ------+---->common.jl
                                               |
                                               |
data_extraction.jl ----------------------------+

where

constants.jl :

if @isdefined constants_provided
    print( "constants.jl already loaded")
else
    print("constants.jl not loaded. Loading...")

    include("common.jl");

    # other code

    df_model_master[!,mean_power_sym] = df_model_master[:,mean_power_sym] .* u"W";
    df_model_master[!, std_power_sym] = df_model_master[:, std_power_sym] .* u"W";
    df_model_master

    constants_provided = true
    print("Done!")
end

common.jl :

if @isdefined common_provided
    print( "common.jl already loaded")
else
    print("common.jl not loaded. Loading...")

    using CSV;
    using DataFrames;
    using Statistics;
    using Unitful;
    using Plots;
    using Plots.PlotMeasures;
    using Debugger;

    # other code

    common_provided = true
    print("Done!")
end

However, when running as a script the “client” code data_analysis.jl, I got this error:

ERROR: LoadError: UndefVarError: @u_str not defined
Stacktrace:
 [1] top-level scope
   @ :0
 [2] include(fname::String)
   @ Base.MainInclude ./client.jl:476
 [3] top-level scope
   @ ~/tesi/heap_lab/setup_heap_lab/Julia/data_analysis.jl:5
 [4] include(fname::String)
   @ Base.MainInclude ./client.jl:476
 [5] top-level scope
   @ REPL[1]:1
in expression starting at /home/alessandro/tesi/heap_lab/setup_heap_lab/Julia/constants.jl:50
in expression starting at /home/alessandro/tesi/heap_lab/setup_heap_lab/Julia/constants.jl:5
in expression starting at /home/alessandro/tesi/heap_lab/setup_heap_lab/Julia/data_analysis.jl:5

where

data_analysis.jl:5 -------> include("constants.jl");

constants.jl:5 -------------> if @isdefined constants_provided

constants.jl:50 --------------> df_model_master[!,mean_power_sym] = df_model_master[:,mean_power_sym] .* u"W";

It’s like the Unitful should have been loaded, but it’s not.

Instead, If I manually call the code in the correct order, it doesn’t throw an error.

Why is it?

Thanks!

10 posts - 4 participants