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.
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.
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.
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.
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.
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With