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

PythonStringVariables

Python Problem Overview


For simplicity this is a stripped down version of what I want to do:

def foo(a):
    # I want to print the value of the variable
    # the name of which is contained in a

I know how to do this in PHP:

function foo($a) {
    echo $$a;
}

global $string = "blah"; // might not need to be global but that's irrelevant
foo("string"); // prints "blah"

Any way to do this?

Python Solutions


Solution 1 - Python

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.)

Solution 2 - Python

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

Solution 3 - Python

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'

Solution 4 - Python

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

tada!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondsaviView Question on Stackoverflow
Solution 1 - PythonEdward LoperView Answer on Stackoverflow
Solution 2 - PythoneresonanceView Answer on Stackoverflow
Solution 3 - PythonstarkView Answer on Stackoverflow
Solution 4 - PythonmaxmView Answer on Stackoverflow