[Tutor] importing variable contents, and variable naming problms

Ibraheem Umaru-Mohammed iumarumo@eidosnet.co.uk
Fri, 30 Aug 2002 12:06:29 +0100


["Thomi Richards"="Thomi"]
Thomi >> 
Thomi >> Hey! i have a rather simple (well, the answer is probably really
Thomi >> simple..) problem:
Thomi >> 
Thomi >> i have a variable called item, which contains 'lion'. i also have a
Thomi >> module called 'lion', and i want to import it. the catch is, the module
Thomi >> will always be called what the contents of the variable is, but the
Thomi >> actual name may change. is there some trick you can do with teh format %
Thomi >> sign thingies??
Thomi >> 

i think you want to use __import__.

e.g
	item = 'lion'
	__import__(item)

Thomi >> similarly, if i have a variable called item, and it contains 'lion', how
Thomi >> can i make a variable named the same as the contents of 'item'?? so i
Thomi >> would end up with two variables, one called 'item', and one called
Thomi >> 'lion'. any ideas guys?? I could never do this in C, maybe python is a
Thomi >> little different??
Thomi >> 

I believe you want to use exec.

e.g
	item = 'lion'
	exec ("%s = 'foo'" % item)

You can't use eval, because eval doesn't accept statements, only
expressions.

Kindest regards,

				--ibz.
-- 
				Ibraheem Umaru-Mohammed 
					"ibz"
			umarumohammed (at) btinternet (dot) com