Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use variable to hold a variable name

HowTo

Use variable to hold a variable name

by  Bong  Posted    (Edited  )
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:
Code:
eval(c)

Now, the variable whose name is x is equal to 42.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top