35

How do I convert a string to the variable name in Python?

For example, if the program contains a object named self.post that contains a variable named, I want to do something like:

somefunction("self.post.id") = |Value of self.post.id|
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Mohit Ranka
  • 3,873
  • 12
  • 40
  • 41

5 Answers5

54

Note: do not use eval in any case where you are getting the name to look up from user entered input. For example, if this comes from a web page, there is nothing preventing anyone from entering:

__import__("os").system("Some nasty command like rm -rf /*")

as the argument. Better is to limit to well-defined lookup locations such as a dictionary or instance using getattr(). For example, to find the "post" value on self, use:

varname = "post"
value = getattr(self, varname)  # Gets self.post

Similarly to set it, use setattr():

value = setattr(self, varname, new_value)

To handle fully qualified names, like "post.id", you could use something like the below functions in place of getattr() / setattr().

def getattr_qualified(obj, name):
    for attr in name.split("."):
        obj = getattr(obj, attr)
    return obj

def setattr_qualified(obj, name, value):
    parts = name.split(".")
    for attr in parts[:-1]:
        obj = getattr(obj, attr)
    setattr(obj, parts[-1], value)
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Brian
  • 113,117
  • 28
  • 106
  • 111
  • 3
    What if there is no 'self'? I.e. you're in global scope. Then I guess vars()['name'] has to be used, or is there a getattr fallback somehow? – BjornW Apr 11 '18 at 08:29
42

As referenced in Stack Overflow question Inplace substitution from ConfigParser, you're looking for eval():

print eval('self.post.id') # Prints the value of self.post.id
Community
  • 1
  • 1
Owen
  • 80,005
  • 21
  • 116
  • 113
20

Also, there is the globals() function in Python which returns a dictionary with all the defined variables. You could also use something like this:

print globals()["myvar"]
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Geo
  • 89,506
  • 114
  • 330
  • 511
17

You could do something like what Geo recommended, or go with:

>>> wine = 'pinot_noir'
>>> vars()[wine] = 'yum'
>>> pinot_noir
'yum'

Note: vars() and globals() are the same, I'm just used to using vars() I'm surprised nobody called me out on this! Anyway, it's vars() and locals() that are the same.

gibson
  • 375
  • 2
  • 12
0

Use this

var="variable name"
def returnvar(strig):
    rtn="return "+string
    exec(rtn)

var will be your string and run returnvar(var) will to return variable

Adhyayan
  • 1
  • 1
  • 1
    Have you attempted this answer on your own? Is there anything `returnvar` does that `eval` does not do? – mrtig Apr 03 '22 at 14:22