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:
Now, the variable whose name is
x is equal to 42.