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

Question

Asked By – dsavi

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?

Now we will see solution for issue: How to get the value of a variable given its name in a string? [duplicate]


Answer

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

This question is answered By – Edward Loper

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0