Python Forum
Creating local variables from a string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Creating local variables from a string (/thread-24466.html)



Creating local variables from a string - peckjonk - Feb-15-2020

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?


RE: Creating local variables from a string - buran - Feb-15-2020

creating variable names dynamically is really bad idea and you should not do this. Use proper data structure instead.
http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html


RE: Creating local variables from a string - ndc85430 - Feb-15-2020

Why do you think you want to do that? What actual problem are you trying to solve?