-3

I am writing code and I wonder how to approach following issue - I want to use variable name in it's value (concatenating with other string for example). For example

variable_01 = 'some_text_variable_01'
variable_02 = 'some_text_variable_02'

when variables are strings, having its names in these strings.

Thank you in advance for your support.

pc131
  • 53
  • 2
  • 5
  • What are you trying to accomplish with this technique? – Scott Hunter Jan 11 '23 at 19:36
  • Isn't it doable in the way that I proposed? – pc131 Jan 11 '23 at 19:37
  • @ScottHunter in fact I am trying to get part of variable name and then execute a function based on it's name and return a string from a list and assign to the value of this variable. – pc131 Jan 11 '23 at 19:39
  • [This](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) is probably what you should be looking at – Ke1vans Jan 11 '23 at 19:39
  • this seems somewhat redundant with this https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string you might find the discussion there useful – boar Jan 11 '23 at 19:40
  • 1
    " I want to use variable name in it's value" *don't do this*. Just use an appropriate data structure. – juanpa.arrivillaga Jan 11 '23 at 20:00

3 Answers3

1

Your are best to use a dictionary for what you want to do.

For example, If you have a script that produces a list of strings. Then you would have the function as such:

x=["var1","var2","var3"]
fd={}
for y in x:
   string=f"some_text_{y}"
    fd[y]=string

this will give you a dictionary that then contains the "variable" and string pair.

thejahcoop
  • 160
  • 11
0

Many people are going to correctly point out that a dictionary is likely what you really want to use. However, there is a way to do what you seek by leveraging the dictionary provided by globals().

While I do not recommend it, this is technically possible:

name = "variable_01"
globals()[name] = f"some_text_{name}"
print(variable_01)

Your IDE will likely complain about it, but when you run that you should see:

some_text_variable_01

JonSG
  • 10,542
  • 2
  • 25
  • 36
-1

I got it working!

pip install varname

then:

from varname import varname

def func():
  return varname()

variable_01 = func()
print(variable_01)

and the result of executing the script:

C:/Users/some_user/.../Python311/python.exe c:/Users/some_user/project/test_varname.py

variable_01
pc131
  • 53
  • 2
  • 5