Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "dynamically" create local variables in Python? [duplicate]

Is it possible to create a local variables with Python code, given only the variable's name (a string), so that subsequent calls to "'xxx' in locals()" will return True?

Here's a visual :

>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> (...some magical code...)
>>> 'iWantAVariableWithThisName' in locals()
True

For what purpose I require this trickery is another topic entirely...

Thanks for the help.

like image 503
MitchellSalad Avatar asked Jan 10 '12 06:01

MitchellSalad


People also ask

How do you dynamically create a variable in Python?

Create a Dynamic Variable Name in Python Using for Loop Iteration may be used to create a dynamic variable name in Python. This approach will also use the globals() function in addition to the for loop. Python's globals() function returns a dictionary containing the current global symbol table.

What is dynamic local variable?

In a high-level language, non-static local variables declared in a function are stack dynamic local variables by default. Some C++ texts refer to such variables as automatics. This means that the local variables are created by allocating space on the stack and assigning these stack locations to the variables.

How do I change the value of a variable dynamically in Python?

You can use a local dictionary and put all the dynamic bindings as items into the dictionary. Then knowing the name of such a "dynamic variable" you can use the name as the key to get its value. Save this answer.

What is dynamically typed in Python?

Dynamic typing means that the type of the variable is determined only during runtime. Due to strong typing, types need to be compatible with respect to the operand when performing operations. For example Python allows one to add an integer and a floating point number, but adding an integer to a string produces error.


2 Answers

If you really want to do this, you could use exec:

print 'iWantAVariableWithThisName' in locals()
junkVar = 'iWantAVariableWithThisName'
exec(junkVar + " = 1")
print 'iWantAVariableWithThisName' in locals()

Of course, anyone will tell you how dangerous and hackish using exec is, but then so will be any implementation of this "trickery."

like image 97
David Robinson Avatar answered Sep 23 '22 06:09

David Robinson


You can play games and update locals() manually, which will sometimes work, but you shouldn't. It's specifically warned against in the docs. If I had to do this, I'd probably use exec:

>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> exec(junkVar + '= None')
>>> 'iWantAVariableWithThisName' in locals()
True
>>> print iWantAVariableWithThisName
None

But ninety-three times out of one hundred you really want to use a dictionary instead.

like image 34
DSM Avatar answered Sep 24 '22 06:09

DSM