Is it ok to use top level variables in Julia script?

Is it ok to use top level variables in Julia script?
typescript
Ethan Jackson

Is it ok to have following code structure?

lib.jl

report(message) = println("Report: ", message) prepare_data() = "data"

main.jl

includet("./lib.jl") # Revise.includet # Some config top level variables config = "config" doc_before = "Some readme doc..." # Some functions compute(data) = "computed data" # Main script report(doc_before) data = prepare_data() computed = compute(data) report("Computed successfully: $computed") report("Finished")

I heard that having top level variables may reduce Julia computation speed and compilation and re-compilation speed.

Also Revise used in ~/.julia/config/startup.jl and interactive mode with VS Code REPL and Shift+Enter used.

Answer

Yeah it’s totally fine to use top-level variables in a simple Julia script like that — especially for configs and basic flow. But if you’re doing performance-heavy stuff or using Revise a lot, it’s better to wrap things in a main() function and maybe use const for fixed values. Helps with compile times and avoids weird recompile issues. But for most scripts, you're good!

Related Articles