Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to preexisting variable names

Tags:

python

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| 
like image 298
Mohit Ranka Avatar asked Nov 17 '08 07:11

Mohit Ranka


People also ask

How do I convert a string to a variable name?

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.

How do you make a string variable?

How to create a string and assign it to a variable. To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable.

How do you save a string to a variable in Python?

Declaring strings as variables can make it easier for us to work with strings throughout our Python programs. To store a string inside a variable, we need to assign a variable to a string. In this case let's declare my_str as our variable: my_str = "Sammy likes declaring strings."

Can you convert a string to a list?

Strings can be converted to lists using list() .


2 Answers

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) 
like image 196
Brian Avatar answered Sep 28 '22 09:09

Brian


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 
like image 41
Owen Avatar answered Sep 28 '22 09:09

Owen