Python Forum
Looping through variables and setting them
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping through variables and setting them
#7
Using eval and exec is for sure not the way to go.
Think of what happen when do pos1 = 1 Think
>>> pos1 = 1
>>> pos1
1
Internally  is python storing this a dictionary.
>>> globals()
{'__name__': '__main__', 'pos': 1,}
>>> globals()['pos1']
1
We should not do the tricks and using the globals() dictionary.
Making a normal visible dictionary is the way to go.
>>> d = {}
>>> for i in range(1,9):
...     d[f'pos{i}'] = i
...
    
>>> d
{'pos1': 1,
 'pos2': 2,
 'pos3': 3,
 'pos4': 4,
 'pos5': 5,
 'pos6': 6,
 'pos7': 7,
 'pos8': 8}

>>> d['pos1']
1
Reply


Messages In This Thread
RE: Looping through variables and setting them - by snippsat - Dec-17-2017, 02:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Setting permanent user variables in Windows coder420 2 1,484 Jan-04-2022, 10:42 AM
Last Post: Larz60+
  Help Setting Multiple Variables bzowk 0 1,649 Jul-18-2020, 06:59 PM
Last Post: bzowk
  setting pythonpath variable in environment variables saisankalpj 3 3,558 Dec-05-2018, 10:33 PM
Last Post: Gribouillis
  os.environ not setting current shell variables in Windows? brian6667 2 10,942 Apr-26-2017, 12:59 PM
Last Post: brian6667

Forum Jump:

User Panel Messages

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