This may be the long way around the barn but sometimes it comes up that you want the value of a variable, say that it is input from a file, to be the name of a variable in the code. It wasn't obvious to me how to do it and here is at least "a way":
For example, let a='x', that is the value of variable a is the string, 'x'. This could be the result of a file read, like a=f.readline().split()[0], or something. Anyway, the value of the variable, a, is the string that is to be used as a variable name, in this case, "x".
Now we need to use the compile built-in function to build an object that can be evaluated:
Code:
c=compile(a+'=42','<string>','exec')
where "=42" could be any assignment.
Then we use eval() to substitute the value of a (or x) into the compiled object:
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.