Get the name of a function in the argument

I would like to have a function that returns the name of the function in the argument, e.g.:

function give_me_my_name(f::Function)
    return ??? (f);
end

such that

give_me_my_name(sin)

returns

sin

as a string. How do I do that?

2 Likes
julia> function give_me_my_name(f::Function)
           return String(Symbol(f))
       end
give_me_my_name (generic function with 1 method)

julia> give_me_my_name(sin)
"sin"
10 Likes
julia> give_me_my_name(give_me_my_name)
"give_me_my_name"

:grin:

5 Likes

Awesome! Thanks!

The best about Julia is that brought child-like fun of programming back
to me — but a close second is that fantastic helpful & fun
Julia-Community!!! So cool!

4 Likes

How do you do this for a mutable struct?

String(Symbol(X))

does not yield the name…

Its just the same:

julia> mutable struct mutable_struct
       x
       end

julia> typeof(mutable_struct)
DataType

julia> function give_me_my_name(s::DataType)
           return String(Symbol(s))
           end
give_me_my_name (generic function with 2 methods)

julia> give_me_my_name(mutable_struct)
"mutable_struct"
1 Like

You can do it generic:

julia> function give_me_my_name(whatever)
           return String(Symbol(whatever))
           end
give_me_my_name (generic function with 3 methods)

julia> give_me_my_name(Int)
"Int64"
2 Likes

Sorry, I explained myself badly: Variablenames
are only accessible by Macros, right? For

mutable struct mutable_struct
     x
     y
     z
end

var = mutable_struct(1,2,3);

function give_me_my_name(s::mutable_struct)
     return String(Symbol(s))
end

give_me_my_name(var)

I get "mutable_struct(1, 2, 3)" and for the macro, I have

macro give_me_my_name(s)
     String(s)
end
@give_me_my_name(var)

Or is that also possible in a function?

No, I don’t think this is possible with a function. In the function it would be the function parameters name and not var anymore.

You may find interesting this macro that prints the name of the current function it is called from:

2 Likes

It seems no one mentioned the built-in method Base.nameof.

julia> function give_me_my_name(f::Function)
           return string(nameof(f))
       end
give_me_my_name (generic function with 1 method)

julia> give_me_my_name(sin)
"sin"

It also works for a data type.

julia> function give_me_my_name(s::DataType)
           return string(nameof(s))
       end
give_me_my_name (generic function with 1 method)

julia> give_me_my_name(IOStream)
"IOStream"

More interesting utilities can be found in the Reflection part of the documentation.

6 Likes

(Sorry for necro-posting)

Another way I just discovered. It’s not necessary to go via Symbol:

jl> f = sin
sin (generic function with 15 methods)

jl> string(f)
"sin"

Direct string interpolation also works:

jl> "Hello, $(f)!"
"Hello, sin!

Both methods work for types as well.

Going via nameof is much faster, though.

2 Likes