# Best way to create/assign variables based on strings

**URL:** <https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001>\
**Category:** New to Julia\
**Created:** [April 1, 2017, 4:47pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001 "2017-04-01T16:47:43Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![askvorts](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/askvorts/32/7120_2.png) [@askvorts](https://discourse.julialang.org/u/askvorts)\
**Post date:** [April 1, 2017, 4:47pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/1 "2017-04-01T16:47:43Z")

</div>

Hi all

Which would be best way to create/assign variables based on strings. Assuming I have this:

> string = “AA”  
> string = get(“[https://get.some.unknown.very.short.string](https://get.some.unknown.very.short.string)”)

would like to do the following

> AA = 1  
> new\_variable\_named\_on\_that\_yet\_unknown\_short\_string = 1

Thank you!

---

<div class="post-metadata">

**Author:** ![Tero\_Frondelius](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tero_frondelius/32/7629_2.png) [@Tero\_Frondelius](https://discourse.julialang.org/u/Tero_Frondelius)\
**Post date:** [April 1, 2017, 4:52pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/2 "2017-04-01T16:52:57Z")

</div>

Sorry not answering your question, but consider using [JSON.jl](https://github.com/JuliaIO/JSON.jl).

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [April 1, 2017, 5:02pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/3 "2017-04-01T17:02:18Z")

</div>

Use a dictionary: [http://docs.julialang.org/en/stable/stdlib/collections/#Base.Dict](http://docs.julialang.org/en/stable/stdlib/collections/#Base.Dict)

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [April 1, 2017, 5:02pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/4 "2017-04-01T17:02:51Z")

</div>

If this is in global scope. Use `eval`. If this is local scope, it’s impossible and won’t be possible. Use a `Dict` with `String` as keys to hold the value instead.

---

<div class="post-metadata">

**Author:** ![Tero\_Frondelius](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tero_frondelius/32/7629_2.png) [@Tero\_Frondelius](https://discourse.julialang.org/u/Tero_Frondelius)\
**Post date:** [April 1, 2017, 5:06pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/5 "2017-04-01T17:06:34Z")

</div>

Here is the code, but this is not the best practice:

```julia
julia> string = "AA"
"AA"

julia> value = 1
1

julia> eval(parse("$string=$value"))
1

julia> AA
1

julia> 

```

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [April 1, 2017, 5:26pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/6 "2017-04-01T17:26:31Z")

</div>

Even if you want to use `eval`. **DO NOT USE** `parse`.

Do `@eval $(Symbol(string)) = $value` or `@eval $(Symbol(string)) = value`.

---

<div class="post-metadata">

**Author:** ![askvorts](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/askvorts/32/7120_2.png) [@askvorts](https://discourse.julialang.org/u/askvorts)\
**Post date:** [April 2, 2017, 12:48am UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/7 "2017-04-02T00:48:28Z")

</div>

Thank you for all the answers.

> [quote=“yuyichao, post:4, topic:3001, full:true”]  
> If this is in global scope. Use `eval`. If this is local scope, it’s impossible and won’t be possible. Use a `Dict` with `String` as keys to hold the value instead.  
> [/quote]  
> Found a “solution” in local scope by widening the field of permissible functions. In my setting “AA” and “BB” represent those short-strings yet to be fetched  
> `var1 = "AA"`  
> `var2 = "BB"`

but on the contrary, x and y are known at coding time

> `x = 2.0`  
> `y = rand(2,2)`

An ugly solution may be:

> `function crazymeta(file)`  
> ` open(file, "w") do f`  
> ` write(f,"$var1 = x\n$var2 = y")`  
> ` end`  
> ` include("$file")`  
> ` return AA * BB`  
> `end`

> `CC = crazymeta("whatever.jl")`  
> `print("$CC")`

Now `AA = 2.0`, `BB` and `CC` are naturally `2x2 Array{Float64,2}`. Would it possible to do something like this print/include trick, but with all steps in memory and reasonably fast?

---

<div class="post-metadata">

**Author:** ![greg\_plowman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/greg_plowman/32/8100_2.png) [@greg\_plowman](https://discourse.julialang.org/u/greg_plowman)\
**Post date:** [April 2, 2017, 1:09am UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/8 "2017-04-02T01:09:50Z")

</div>

Well you could use `include_string`, but `include` operates at global scope.  
In your example, AA and BB will be defined as global variables.  
In this case, probably best to go with @yuyichao’s suggestion and use `@eval`.

---

<div class="post-metadata">

**Author:** ![fengyang.wang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fengyang.wang/32/104_2.png) [@fengyang.wang](https://discourse.julialang.org/u/fengyang.wang)\
**Post date:** [April 2, 2017, 1:46am UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/9 "2017-04-02T01:46:34Z")

</div>

A better way to write this is

```julia
var1 = "AA"
var2 = "BB"
@eval $(Symbol(var1)) = x
@eval $(Symbol(var2)) = x
CC = AA * BB
print(CC)

```

but again, this is not usually the best way to go about things. What are you trying to do? By that I mean your actual goal, for which this metaprogramming may likely not be the best solution for.

---

<div class="post-metadata">

**Author:** ![NickNack](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nicknack/32/1792_2.png) [@NickNack](https://discourse.julialang.org/u/NickNack)\
**Post date:** [April 2, 2017, 3:46pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/10 "2017-04-02T15:46:25Z")

</div>

> [@yuyichao](#):
>
> If this is local scope, it’s impossible and won’t be possible. Use a `Dict` with `String` as keys to hold the value instead.

I agree that using a Dict is better in most cases. However, by defining a macro it is certainly not impossible to create variables in local scope only. I posted [one possible solution in another thread](https://discourse.julialang.org/t/string-as-a-variable-name/2195/7). Or did I misunderstand what you meant?

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [April 2, 2017, 3:56pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/11 "2017-04-02T15:56:11Z")

</div>

No it’s impossible to create a variable in local scope from runtime value. You can of course use a macro to translate `@m "b"` into `b = 1` but it’s impossible to make `var = "b"; @m var` behave like `b = 1`.

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [April 2, 2017, 3:59pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/12 "2017-04-02T15:59:38Z")

</div>

In another word, if there’s a way to do this (create local variable from runtime value), it’s a semantic bug that needs to be fixed.

---

<div class="post-metadata">

**Author:** ![NickNack](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nicknack/32/1792_2.png) [@NickNack](https://discourse.julialang.org/u/NickNack)\
**Post date:** [April 2, 2017, 3:59pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/13 "2017-04-02T15:59:51Z")

</div>

I see. I should have read the original post more carefullly instead of jumping all over my example in the other thread. Thanks for clarifying!

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [April 2, 2017, 4:03pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/14 "2017-04-02T16:03:50Z")

</div>

Note that the macro is very unlikely the right solution in the other thread either. It essentially let you spell variable syntax slight differently, like writing `"a" = 1` instead of `a = 1`, which might be cool if you really like quoting but I don’t think that’s what the OP asked about in either thread.

---

<div class="post-metadata">

**Author:** ![NickNack](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nicknack/32/1792_2.png) [@NickNack](https://discourse.julialang.org/u/NickNack)\
**Post date:** [April 2, 2017, 4:35pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/15 "2017-04-02T16:35:51Z")

</div>

Sorry for nagging, but there is obviously something I still don’t understand. The macro in the other thread seems to work (the function creates a random runtime value and the macro creates a variable with that value in the local scope). Here’s the code:

```julia
macro localvariable(s::AbstractString, v::Any)
	s = Symbol(s)
	esc(:($s = $v))
end

function newtest()
    c = rand()  
    @localvariable("b", c)
    println("b in function = $b")
end

newtest()
isdefined(:b) && println("global b = $b")
nothing

```

Output:

```julia
b in function = 0.8428874752942634

```

What am I missing?

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [April 2, 2017, 4:41pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/16 "2017-04-02T16:41:09Z")

</div>

What you are missing is that the macro isn’t useful other than making it possible to do things like

> [@yuyichao](#):
>
> writing “a” = 1 instead of a = 1

It does **NOT** create a variable whose name is determined at runtime, merely changing how you spell assignments. Also, it’s missing `esc`.

---

<div class="post-metadata">

**Author:** ![varun7rs](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@varun7rs](https://discourse.julialang.org/u/varun7rs)\
**Post date:** [April 26, 2017, 9:49am UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/17 "2017-04-26T09:49:38Z")

</div>

I have a use case for which I could probably use strings as variable names. I want to construct a graph with some vertices. Since I want to create them iteratively, I use a for loop here but this doesn’t work as expected.

```julia
for i = 1:max_nodes
  @eval $(Symbol("V$i")) = ExVertex(i, "V$i")
end

```

So, I switched back to your primary suggestion of using Dictionaries. So far, they work fine.

```julia

vertices = Dict("V$i" => ExVertex(i, "V$i") for i=1:max_nodes)

```

---

<div class="post-metadata">

**Author:** ![Julialang261](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/julialang261/32/22233_2.png) [@Julialang261](https://discourse.julialang.org/u/Julialang261)\
**Post date:** [February 23, 2021, 7:46pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/18 "2021-02-23T19:46:51Z")

</div>

I am replying here to the person who said never to use “parse”.Please excuse if I’ve put my posting in a wrong place, and move it if you can. If yes, I apologize for not being good at social media.  
This response is human, not technical, from an old Assembler Language programmer who even keypunched his own COBOL programs and also wrote supervisor mode Operating System code (MVS) in IBM. Don’t tell persons who have been thru the mill what they cannot do because they’ve had far too much of that from IBM’s (Idiots who Became Manages) and other people who were part of the problem, not part of the solution. If you tell me not to do something, I will want to do it; tell me to do it and I’ll want not to do it. I am a disabled veteran of the Great GOTO War, which left a very bad taste in my mouth. If you tell me that “parse” may not be supported in a future release, I’m all ears to listen to you, because I’ve been burnt by that kind of stuff, too. But “thou shalt not” just reminds me of the True Believers in “Improved Programing Technologies” and my intrusive parents. Respectfully.

---

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [February 23, 2021, 10:44pm UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/19 "2021-02-23T22:44:21Z")

</div>

@Julialang261, you should tell us more about the interesting “Great GOTO War”.  
What about considering a post in the Meta Discussion category? Maybe it would deserve a dedicated “Computing Histories” tag.  
💾

---

<div class="post-metadata">

**Author:** ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)\
**Post date:** [February 24, 2021, 1:01am UTC](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001/20 "2021-02-24T01:01:13Z")

</div>

While @yuyichao could have given an explanation at the time, instead of just a negative and an alternative, the reason is simple: you are doing a lot of unnecessary work by parsing from a `String` to get the expression object to be `eval`uated, using `@eval` and interpolation allows you to build the expression object directly, without a parsing phase.

[Next page](https://discourse.julialang.org/t/best-way-to-create-assign-variables-based-on-strings/3001.md?page=2)
