The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Is It Possible To &Quot;Dynamically&Quot; Create Local Variables In Python?
00:33 Accepted Answer Score 9
00:53 Answer 2 Score 5
01:17 Thank you

--

Full question
https://stackoverflow.com/questions/8799...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #variables #memory #local #instantiation

#avk47



ACCEPTED ANSWER

Score 9


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




ANSWER 2

Score 5


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.