Convert a string to preexisting variable names

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)

Leave a Comment