# Return the variable name as a String

**URL:** <https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340>\
**Category:** New to Julia\
**Created:** [May 24, 2023, 3:50pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340 "2023-05-24T15:50:55Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![geo1093](https://avatars.discourse-cdn.com/v4/letter/g/5f9b8f/32.png) [@geo1093](https://discourse.julialang.org/u/geo1093)\
**Post date:** [May 24, 2023, 3:50pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/1 "2023-05-24T15:50:55Z")

</div>

Hi,  
Is it possible to define a function, structure, macro or whatever to get sth like this:

> julia\> a = somefunc()  
> “a”

where the string contains the variable name ? I would like a way to print the variable name without writing it twice (once for the declaration and once for the string).

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [May 24, 2023, 3:55pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/2 "2023-05-24T15:55:11Z")

</div>

no, the right hand side of `=` can’t see what’s left to it. Because the right-hand side has to be “evaluated” first, and the return value is bonded to left-hand side (variable name)

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [May 24, 2023, 3:56pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/3 "2023-05-24T15:56:21Z")

</div>

> [@geo1093](#):
>
> writing it twice (once for the declaration and once for the string).

what you’re looking for is `@show`:

```julia
julia> a = 2.03;

julia> @show a;
a = 2.03

```

---

<div class="post-metadata">

**Author:** ![fatteneder](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fatteneder/32/33991_2.png) [@fatteneder](https://discourse.julialang.org/u/fatteneder)\
**Post date:** [May 24, 2023, 3:59pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/4 "2023-05-24T15:59:39Z")

</div>

EDIT: This answer is obsolete after OP updated the question to include

> I would like a way to print the variable name without writing it twice (once for the declaration and once for the string).

@jling gave the correct answer above.

* * *

I feel like your syntax is a bit off.

Maybe you want to do something like

```julia
julia> macro stringify(ex)
           return esc(string(ex))
       end
@stringify (macro with 1 method)

julia> name_a = @stringify a
"a"

```

But the question is, why not just write

```julia
julia> name_a = "a"

```

in the first place?

---

<div class="post-metadata">

**Author:** ![geo1093](https://avatars.discourse-cdn.com/v4/letter/g/5f9b8f/32.png) [@geo1093](https://discourse.julialang.org/u/geo1093)\
**Post date:** [May 24, 2023, 4:15pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/5 "2023-05-24T16:15:51Z")

</div>

Thank you for your answers.

> [@fatteneder](#):
>
> But the question is, why not just write
> 
> ```julia
> julia> name_a = "a"
> 
> ```
> 
> in the first place?

Because I have plenty of parameters to play with, and I would like a way to access their names as Strings without writing for each parameter

> name(very\_long\_parameter\_name)=“very\_long\_parameter\_name”

---

<div class="post-metadata">

**Author:** ![Nathan\_Boyer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nathan_boyer/32/14825_2.png) [@Nathan\_Boyer](https://discourse.julialang.org/u/Nathan_Boyer)\
**Post date:** [May 24, 2023, 5:23pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/6 "2023-05-24T17:23:43Z")

</div>

You can get all “names” defined in a module with `names(module_name)`.

```julia
julia> x = 3
3

julia> y = 5
5

julia> names(Main)
7-element Vector{Symbol}:
 :Base
 :Core
 :InteractiveUtils
 :Main
 :ans
 :x
 :y

```

Also, see the VSCode Workspace for that same information.  
 ![image](https://global.discourse-cdn.com/julialang/original/3X/e/4/e439b32f471310d4bebadf7ae31d234ca353da7f.png)

However, that is only going to work for global variables which should generally be avoided (unless they are `const`). I suggest instead you put all your parameters into a `NamedTuple` (or a Dictionary if you don’t know all of the parameters ahead of time) and work with that instead.

```julia
julia> parameters = (a=1, b="hello")
(a = 1, b = "hello")

julia> keys(parameters)
(:a, :b)

julia> string.(keys(parameters))
("a", "b")

```

Named Tuples are faster to use than Dictionaries but the names will be stored as `Symbol` rather than `String`. Dictionaries can use strings directly as keys and you can add to them after creation.

```julia
julia> params = Dict("c" => 8.8)
Dict{String, Float64} with 1 entry:
  "c" => 8.8

julia> params["d"] = 10
10

julia> params
Dict{String, Float64} with 2 entries:
  "c" => 8.8
  "d" => 10.0

julia> keys(params)
KeySet for a Dict{String, Float64} with 2 entries. Keys:
  "c"
  "d"

```

---

<div class="post-metadata">

**Author:** ![davide](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/davide/32/52136_2.png) [@davide](https://discourse.julialang.org/u/davide)\
**Post date:** [May 24, 2023, 5:46pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/7 "2023-05-24T17:46:27Z")

</div>

Hi @geo1093 , this may be a possible different solution.

1. Store variables names (as strings) in a vector, or any other variable, (so you write them only once):

```julia
names = ["A", "B"]

```

1. Define a function to create a variable from a string and assign a value to it (example from Lee Phillips’s book “Practical Julia”):

```julia
mkvar(s, v) = eval(:($(Symbol(s)) = $v))

```

1. Use the `mkvar()` function with the strings stored in variable `names`:

```julia
mkvar(names[1], 1:3)
# which produce the variable `A` as with the command:
A = 1:3

```

1. For the reverse (reading the values stored in the variables given the variables names specified as strings), define the function:

```julia
readvar(s) = eval(:($(Symbol(s))))

```

1. Use function `readvar()` with the strings stored in `names` to read the values in the corresponding variables;:

```julia
readvar(names[1])

```

---

<div class="post-metadata">

**Author:** ![mkitti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkitti/32/12459_2.png) [@mkitti](https://discourse.julialang.org/u/mkitti)\
**Post date:** [May 24, 2023, 6:35pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/8 "2023-05-24T18:35:21Z")

</div>

A macro is what you want I think. For example, I used one in Napari.jl to the [stringify the expression of the image I’m trying to show while also passing it](https://github.com/mkitti/Napari.jl/blob/b2c1469599ce14911efb3a90286c48c59d2dda2d/src/layer_name_macros.jl#L15-L20).

```julia
julia> macro namekw(expr)
           ( isa(expr,Expr) && expr.head == :call ) ||
               error("@namekw must be used on a method call.")
           push!( expr.args, Expr( :kw, :name, string(expr.args[2]) ) )
           esc( expr )
       end
@namekw (macro with 1 method)

julia> f(args...; kwargs...) = args, kwargs
f (generic function with 1 method)

julia> f(a)
((5,), Base.Pairs{Symbol, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}())

julia> @namekw f(a)
((5,), Base.Pairs(:name => "a"))

```

More succintly

```julia
julia> g(x; name=nothing) = x, name
g (generic function with 1 method)

julia> @namekw g(a)
(5, "a")

julia> value, variable = @namekw g(a)
(5, "a")

julia> value
5

julia> variable
"a"

```

---

<div class="post-metadata">

**Author:** ![Nathan\_Boyer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nathan_boyer/32/14825_2.png) [@Nathan\_Boyer](https://discourse.julialang.org/u/Nathan_Boyer)\
**Post date:** [May 25, 2023, 2:20pm UTC](https://discourse.julialang.org/t/return-the-variable-name-as-a-string/99340/9 "2023-05-25T14:20:20Z")

</div>

> [@geo1093](#):
>
> name(very\_long\_parameter\_name)=“very\_long\_parameter\_name”

Nested collections may also help avoid such long variable names. Accessing the variables directly with dot syntax isn’t any shorter (e.g. `parameters.files.schedule`), but collections can make it easier to pass only relevant variables to functions.

```julia
julia> function list_employees(employees)
           for name in values(employees)
               println(name)
           end
       end
list_employees (generic function with 1 method)

julia> parameters = (
           files = (
               schedule = "Documents/schedule.xlsx",
               output = "Documents/out.txt",
           ),
           employees = (
               CEO = "John",
               manager = "Barb",
               cashier = "Fred",
           ),
           minimum_wage = 7.50,
       )
(files = (schedule = "Documents/schedule.xlsx", output = "Documents/out.txt"), employees = (CEO = "John", manager = "Barb", cashier = "Fred"), minimum_wage = 7.5)

julia> list_employees(parameters.employees)
John
Barb
Fred

```

It is also common to rename a variable to something shorter at the top of a function where the context is more clear and then do the real work with those shorter names.

```julia
function update_schedule(parameters)
    schedule = parameters.files.schedule
    cashier = parameters.employees.cashier
    # do stuff
end

```
