How to get the name of the current function

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)`"
julia> foo()
ERROR: UndefVarError: fname not defined
 [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?

1 Like

How about stacktrace

julia> function foo()
       funcname = StackTraces.stacktrace()[1].func
foo (generic function with 1 method)

julia> foo()

There is also @__FILE__ and friends.


You have an interpolation problem, trying to interpolate into a string and into @eval at the same time. Try this instead:

for fname in (:foo, :bar)
    @eval $fname() = string("This function is `", $fname, "`")

Both suggestions are fine. @GunnarFarneback’s fits better my actual suit case. Thanks!

I was curious if this was defined anywhere in Base—because I thought it must be used for convenience in some places—and it is there but unexported:

julia> Base._counttuple(Tuple{Any, Any, Any, Any})

For more general types, you can use fieldcount also.

For completeness and to answer the post title directly:

julia> function myfunc()
           name = nameof(var"#self#")
           println("This function is $name")
myfunc (generic function with 1 method)

julia> myfunc()
This function is myfunc

although this relies on undocumented internals I think. See also