views:

1247

answers:

5

How do I accomplish this in Python? Here is an elaborative manual entry, for instance :http://us3.php.net/manual/en/language.variables.variable.php

I hear this is a bad idea in general though, and it is a security hole in PHP. I'm curious if anyone knows how as well?

+8  A: 

Use dictionaries to accomplish this. Dictionaries are stores of keys and values.

>>> dict = { 
    'x': 1, 
    'y': 2, 
    'z': 3
}
>>> dict
{'y': 2, 'x': 1, 'z': 3}
>>> dict['y']
2

You can use variable key names to achieve the effect of variable variables without the security risk.

>>> x = 'spam'
>>> z = { x: 'eggs' }
>>> z['spam']
'eggs'

Make sense?

cpharmston
I'm afraid I don't understand too well. Can you explain?
http://docs.python.org/library/stdtypes.html#dict
Corey D
Edited my answer to explain dictionaries.
cpharmston
Yeah, I understand now. Thanks.
+7  A: 

Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing

$foo = "bar"
$$foo = "baz"

you write

mydict = {}
foo = "bar"
mydict[foo] = "baz"

This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".

sepp2k
+1, a good way to explain it.
Nadia Alramli
Ah. That makes sense.
+5  A: 

can be easily accomplished with built-in getattr.

getattr(obj, 'foobar')
SilentGhost
+6  A: 

It's not a good idea. If you are accessing a global variable you can use globals()

>>> a = 10
>>> globals()['a']
10

If you want to access a variable in the local scope you can use locals()

A better solution is to use getattr or store your variables in a dictionary and then access them by name.

Nadia Alramli
+1 answering the question as stated (even though it's horrible)
bobince
Don't forget to mention that you can't modify variables through locals() (http://docs.python.org/library/functions.html#locals).
Glenn Maynard
+1  A: 

You could also use exec and eval:

newvar = 'x'
newvalue = 12
exec('%s=%d') % (newvar, newvalue)
#this will print 12
print x
#this will print 12 as well
print eval(newvar)
Mauro Bianchi
This is by far the worst way to do it.
Nadia Alramli
This is definitely true, but it depends by the context you are. It's a quick and dirty solution. I think getattr the best one.
Mauro Bianchi
Ugh, never use eval.
cpharmston
No reason to use eval/exec here, globals()/locals() are perfectly adequate and don't have weird problems where ‘newvalue’ is something that doesn't repr() well.
bobince
New problems with execs in Python 3.0
whatnick