[Tutor] importing variable contents, and variable naming prob
lms
alan.gauld@bt.com
alan.gauld@bt.com
Fri, 30 Aug 2002 12:49:12 +0100
>>> can i make a variable named the same as the contents of 'item'??
You can but its nearly always a bad idea.
Usually you woyuld be better creating a dictionary
storing your 'variables' by name.
vars = {}
items = ['foo','bar','baz']
for item in items:
vars[item] = ord(item[0])
for item in items:
print vars[item]
>>> 'lion'. any ideas guys?? I could never do this in C,
>>> maybe python is different
> I believe you want to use exec.
> item = 'lion'
> exec ("%s = 'foo'" % item)
You can do it but it's risky - too easy to accidentally
get name collisions etc. Also running exec is risky from
a security point of view:
item = 'rm -rf /' # load this from someplace...
exec(item) # oops!!
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld