Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of a variable given its name in a string? [duplicate]

People also ask

How do I get the value of a variable in Python?

Python variables store values in a program. You can refer to the name of a variable to access its value. The value of a variable can be changed throughout your program. Variables are declared using this syntax: name = value.

How do you find the value of a variable?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back.

How do you use a string name as a variable in Python?

String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.


If it's a global variable, then you can do:

>>> a = 5
>>> globals()['a']
5

A note about the various "eval" solutions: you should be careful with eval, especially if the string you're evaluating comes from a potentially untrusted source -- otherwise, you might end up deleting the entire contents of your disk or something like that if you're given a malicious string.

(If it's not global, then you'll need access to whatever namespace it's defined in. If you don't have that, there's no way you'll be able to access it.)


Edward Loper's answer only works if the variable is in the current module. To get a value in another module, you can use getattr:

import other
print getattr(other, "name_of_variable")

https://docs.python.org/3/library/functions.html#getattr


Assuming that you know the string is safe to evaluate, then eval will give the value of the variable in the current context.

>>> string = "blah"
>>> string
'blah'
>>> x = "string"
>>> eval(x)
'blah'

>>> x=5
>>> print eval('x')
5

tada!