1

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.

1

6 Answers 6

5

When you want variably-named variables, it's time to use a dictionary:

data = {}
foo = 'bar'
data[foo] = 'baz'
print data['bar']
Sign up to request clarification or add additional context in comments.

10 Comments

This was not my question, my question was how to set local variables, no how to workaround that need
@AsTeR: you should accept one of the other answers then. Also, you should stop trying to do this. Dictionaries were meant to solve this problem.
I know dictionary exist, I also know that I should accept answer on SO if any fits my question. And I also know what I do, thanks for caring (the edit of the question explains a bit that point) !
@AsTeR: Please read Ned's nice blog post Keep data out of your variable names (in particular the discussion). And please consider the possibility that you are wrong on this one.
@AsTeR: In that case, I suggest to make config an instance of a custom class, and to use setattr() and getattr(). Dynamically named attributes have their use cases, but dynamically named variables don't. (This seems to be an instance of the XY problem: You did not ask about your actual problem, but about the attempted solution.)
|
3

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.

Comments

3

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.

1 Comment

+1 for detailed code, I accepted Sven's answer for being the first !
1

At the module level you can use setattr on the current module, which you can get from sys.modules:

setattr(sys.modules[__name__], 'name', 'value')

Comments

0

The locals() function returns a dictionary filled with the local variables.

locals()['foo'] = 'baz'

2 Comments

That do not work inside of a function indeed, but outside it works
@AsTeR: Then you should be using globals() instead of locals(). The documentation of locals() states that the returned dictionary must not be modified.
0

Are you looking for functions like these? They allow modifying the local namespace you happen to be in.

import sys

def get_var(name):
    return sys._getframe(1).f_locals[name]

def set_var(name, value):
    sys._getframe(1).f_locals[name] = value

def del_var(name):
    del sys._getframe(1).f_locals[name]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.