Load functions from files dynamically without including them in global scope

I want to dynamically include functions from files based on condition.

Below code gives you an Idea.

File1.jl

function foo()
    println("In File1.jl")
end

File2.jl

function foo()
    println("In File2.jl")
end

Main.jl

function main(get_func_from)
    if get_func_from=="File1.jl"
        include("File1.jl")
        foo()
    end
end

Please note that I don’t want to include File1, File2 under global scope and want to call foo and include file only when needed.

You cannot do that. include works only at global scope for the same reason as eval only works at global scope (include really is eval-this-file), namely performance. If you could eval into local scope, Julia’s compilation-scheme would not work anymore. This limitation is really at the heart why Julia is fast.

Try to formulate your problem as a dispatch problem instead. Or just call into different functions in a if-else statement.

3 Likes