Is there something equivalent to deparse(substitute(x)) in Julia?

Dear all,

coming from R, I used to use deparse(substitute(x)) to get the name of an object x as a string. Is there anything similar in Julia?

Thanks in advance!

1 Like

Hi julianjohs, welcome to Julia Discourse.

The short answer is no.

In Julia, there is no concept of an object having one name. It may have multiple bindings (i.e., ways to refer to it) in multiple scopes. It may be called x in your global scope, and passed to a method in which (inside the method) it is called y, for example. All these names are external to the object and the object itself is not aware of any of them.

The long answer is it depends.

Using macros, Julia allows you to capture an expression. For example,

julia> x = 10
10

julia> @show x
x = 10
10

julia> @show x + 10
x + 10 = 20
20

But this is, probably, much more limited than what you want. In Julia, macros cannot do anything the programmer could not do by hand, with a little more effort and repetition of code. So, they only serve to automate code patterns. In your case, it seems like you will need to write code that pass an object and a name for it to be used, macros can help you to do that, but this does not change the fact you (yourself, not the language) is making the effort of passing a String together with an arbitrary object.

Example on how to achieve it:

struct NamedObject{T}
    name :: String
    object :: T
end

macro wrap_name(expression)
    quote
        NamedObject(string($(Meta.quot(expression))), $expression)
    end
end

@wrap_name(log10(1000))

returns

NamedObject{Float64}("log10(1000)", 3.0)
4 Likes