Python Forum
Creating local variables from a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating local variables from a string
#1
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?
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variables in a SCPI string thomaswfirth 3 906 May-22-2023, 05:04 PM
Last Post: thomaswfirth
  Global variables or local accessible caslor 4 1,020 Jan-27-2023, 05:32 PM
Last Post: caslor
  Creating a loop with dynamic variables instead of hardcoded values FugaziRocks 3 1,482 Jul-27-2022, 08:50 PM
Last Post: rob101
  Referencing string names in df to outside variables illmattic 1 1,358 Nov-16-2021, 12:47 PM
Last Post: jefsummers
  Creating new column with a input string drunkenneo 2 2,245 Apr-14-2021, 08:10 AM
Last Post: drunkenneo
  Global vs. Local Variables Davy_Jones_XIV 4 2,650 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 4,232 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  Creating a variables inside FOR loop zazas321 5 4,098 Sep-16-2020, 04:42 PM
Last Post: Naheed
  Question regarding local and global variables donmerch 12 5,075 Apr-12-2020, 03:58 PM
Last Post: TomToad
  local/global variables in functions abccba 6 3,429 Apr-08-2020, 06:01 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020