0

If I had the following code:

random_variable = "Hello World"
new_value = "It Works!"

And I had something like this:

def set_variable_value(var_name, new_value):
    // Code here
    pass

Is it possible to have a function like the one above where var_name is a string? It should take var_name and find a variable named the value of the string, and change the value to whatever new_value is.

I'm sorry if this is a dumb question, I searched the web for a while now and discovered nothing related to my issue. (Google is being useless as usual)

Thanks

Eric
  • 678
  • 3
  • 20
  • 2
    You'll want a dictionary. `my_data = {"random_variable": "Old value"}` ... – AKX Jan 01 '22 at 21:02
  • 1
    Do not modify variable name dynamically, this **will** cause you more trouble than you expect to solve – mozway Jan 01 '22 at 21:13

1 Answers1

1

You could do this:

def set_variable_value(var_name, new_value):
    globals()[var_name] = new_value

However, this could be considered an anti-pattern. Consider using a dictionary instead and using the values as my_dictionary[some_string].

Dennis
  • 2,249
  • 6
  • 12