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?

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"
4 Likes
julia> give_me_my_name(give_me_my_name)
"give_me_my_name"

:grin:

1 Like

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!

1 Like

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"

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:

1 Like