1

You can call variables through a loop in Python like this:

var1 = 1
var2 = 2
var3 = 3

for i in range(1,4):
    print(globals()[f"var{i}"])

This results in:

1
2
3

Now I'm looking for the equivalent way to call variables using interpolated strings in Julia! Is there any way?

PS: I didn't ask "How to get a list of all the global variables in Julia's active session". I asked for a way to call a local variable using an interpolation in a string.

mbauman
  • 30,958
  • 4
  • 88
  • 123
Shayan
  • 5,165
  • 4
  • 16
  • 45
  • 2
    Don't even do that in Python. Use a list. – user2357112 Jul 18 '22 at 18:14
  • @user2357112 I would appreciate it if you explain the reason. – Shayan Jul 18 '22 at 18:16
  • Why do you want to use globals in the first place? – ndc85430 Jul 18 '22 at 18:19
  • Does this answer your question? [Get a list of current variables in Julia Lang](https://stackoverflow.com/questions/21301451/get-a-list-of-current-variables-in-julia-lang) – Silvio Mayolo Jul 18 '22 at 18:20
  • @ndc85430 for the sake of convenience in some situations, especially in loops. – Shayan Jul 18 '22 at 18:20
  • 2
    The linked question has your answer, but I echo the sentiments already expressed here. Lists, in both Julia and Python, are built for this purpose. Reflection is an advanced feature, and using it to fake arrays is like using a nuclear missile to drill a hole in a bookshelf. You're going to confuse everybody and risk introducing a lot of additional problems, even if it does technically solve the problem at hand. – Silvio Mayolo Jul 18 '22 at 18:21
  • @SilvioMayolo No, it doesn't. I tried `whos()` and `varinfo()`. It doesn't work. Although my question is different, I didn't ask for a list of global variables! – Shayan Jul 18 '22 at 18:22
  • Nope, you have the wrong approach. If you have a collection of things, you should use a collection (like an array). Dynamically accessing variables like this just leads to code that's hard to understand and maintain. – ndc85430 Jul 18 '22 at 18:23

3 Answers3

3

PS: this is dangerous.
Code:

var1 = 1
var2 = 2
var3 = 3

for i in 1:3
    varname = Symbol("var$i")
    println(getfield(Main, varname))
end
Elias Carvalho
  • 286
  • 1
  • 5
1

List of globals:

vars = filter!(x -> !( x in [:Base, :Core, :InteractiveUtils, :Main, :ans, :err]), names(Main))

Values of globals:

getfield.(Ref(Main), vars)

To display names and values you can either just use varinfo() or eg. do DataFrames(name=vars,value=getfield.(Ref(Main), vars)).

Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
1

You don't. Use a collection like an array instead:

julia> values = [1, 2, 3]
3-element Vector{Int64}:
 1
 2
 3

julia> for v in values
           println(v)
       end
1
2
3

As suggested in earlier comments, dynamically finding the variable names really isn't the approach you want to go for.

ndc85430
  • 1,395
  • 3
  • 11
  • 17