I want to meta-program functions that include messages with their names. This works:
fname = :foo
@eval $fname() = "This function is `$(fname)`"
julia> foo()
"This function is `foo`"
But this doesn’t:
for fname in (:foo, :bar)
@eval $fname() = "This function is `$(fname)`"
end
julia> foo()
ERROR: UndefVarError: fname not defined
Stacktrace:
[1] foo() at ./REPL[27]:2
[2] top-level scope at REPL[28]:1
(Or if the previous example has been executed before, both foo() and bar() print "This function is `foo`")
It seems that the fname interpolated in the string inside the function body is searched in the global scope, so the function name defined locally in the loop is missed.
How could I do this?
Or alternatively, is there any magic trick to get the name of a function inside its body, e.g. a function or macro that returns the name of the function where it has been called?
For completeness and to answer the post title directly:
julia> function myfunc()
name = nameof(var"#self#")
println("This function is $name")
end
myfunc (generic function with 1 method)
julia> myfunc()
This function is myfunc