Python Forum

Full Version: Creating local variables from a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need to create local variables whose names come from an externally specified string. I tried
vars()[varname] = somevalue
This code ran without an error, but it did not create the variable whose name was given in varname.
The vars() doc says
"Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored."

If I do the same thing with globals
globals()[varname] = somevalue
the variable is created but is, of course, global.

Why the restriction with vars and local? And is there a way to create a local variable?
creating variable names dynamically is really bad idea and you should not do this. Use proper data structure instead.
http://stupidpythonideas.blogspot.com/20...reate.html
Why do you think you want to do that? What actual problem are you trying to solve?