Search code examples
pythonvariablesmemorylocalinstantiation

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


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.


Solution

  • 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."