Julia Eval and World Age
Eval and world age describe how code defined at run time becomes callable. New code is defined in module scope, but code compiled before it may not call it directly.
Eval can run quoted code at run time
The quoted multiplication runs when eval runs it.
println(eval(:(3 * 7)))Eval can define a name in module scope
The quoted assignment defines answer, and the next line prints it.
eval(:(answer = 40 + 2))
println(answer)Old compiled code cannot call a new definition directly
The function is compiled before the new definition exists inside its body. The direct call fails and is caught, while the newest-age call returns 77.
function attempt()
eval(:(brand_new() = 77))
try
return brand_new()
catch
return -1
end
end
println(attempt())
println(Base.invokelatest(brand_new))Example
eval(:(answer = 40 + 2))
println(answer)
function attempt()
eval(:(brand_new() = 77))
try
return brand_new()
catch
return -1
end
end
println(attempt())
println(Base.invokelatest(brand_new))Key points
- Eval call: eval takes quoted code and defines it in module scope at run time.
- Quoted code: Quoted code is code held as data until eval runs it.
- Compiled code: Code compiled before the new definition cannot call it directly.
- World age error: A direct call from old compiled code fails, and the error must be caught.
- Newest call: invokelatest calls a function through the newest world age, so the new definition runs.
In this example, eval defines answer as 42, attempt catches its failed direct call with minus 1, and the newest-age call returns 77.
Note
A call from the top level after the definition runs in the newest age, so it does not show the error.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does invokelatest do?