Q:

How to set a variable by its name in Python?

EDIT 2 : since so many people are crying against the bad design this usecase can reveal. Readers of these question and answers should think twice before using it
I've trying to set a variable (not property) by it's name in Python :
foo = 'bar'
thefunctionimlookingfor('foo', 'baz')
print foot #should print baz

PS : the function to access a variable by its name (without eval) would be a plus !
EDIT : I do know dictionary exists, this kind of usage is discouraged, I've choose to use it for a very specific purpose (config file modification according to environment), that will let my code easier to read.

A:

When you want variably-named variables, it's time to use a dictionary:
data = {}
foo = 'bar'
data[foo] = 'baz'
print data['bar']

A:

Dynamically setting variables in the local scope is not possible in Python 2.x without using exec, and not possible at all in Python 3.x.  You can change the global scope by modifying the dictionary returned by globals(), but you actually shouldn't.  Simply use your own dictionary instead.

A:

You can do something like:
def thefunctionimlookingfor(a, b):
    globals()[a] = b

Usage:
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'q' is not defined
>>> thefunctionimlookingfor('foo', 'bar')
>>> foo
'bar'

But this is a terrible idea, as others have mentioned.  Namespaces are a useful concept.  Consider a redesign.

