Python Forum
vars() can't be used in list interpretation?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
vars() can't be used in list interpretation?
#1
P.S. I am not sure why this the interpreter in this site does not recognize vars()... however, it appears that the interpreter in W3Schools works just fine with vars.

I am using vars() and globals(). I am not sure whether this is a good practice, do let me know if it isn't!
This works

x=10
y=5
xy_wsp = [('x','x'),('y','y')]
lst = [lv for v,lv in xy_wsp]
vars()[lst[0]]
For-looping it,

new_lst = []
for lv in lst:
    new_lst.append(vars()[lv])
However, if I use in a list interpretation,

[vars()[lv] for lv in lst]
Then I get
Error:
KeyError: 'x'
Somehow,

[globals()[lv] for lv in lst]
works.

Any idea why? Thanks in advance!
Reply


Messages In This Thread
vars() can't be used in list interpretation? - by Cheng - Jun-22-2021, 10:38 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  This is an Object - Code interpretation JoeDainton123 2 2,539 Jun-16-2021, 08:11 PM
Last Post: snippsat
  English interpretation of the following file handing snippet mortch 5 4,217 May-30-2019, 08:10 AM
Last Post: mortch
  using vars from one file to match lines in another gt76_noobster 3 3,313 Jan-30-2019, 05:34 PM
Last Post: ichabod801
  Vars and getattr problem catosp 5 5,213 Aug-28-2018, 02:54 PM
Last Post: buran
  A help whit vars and strings dhoyosg 10 7,034 May-05-2018, 08:52 AM
Last Post: dhoyosg
  Interpretation of a code Alberto 1 2,650 Jan-02-2018, 06:46 PM
Last Post: Windspar
  What should I name these vars RickyWilson 1 2,826 Dec-03-2017, 03:49 AM
Last Post: nilamo

Forum Jump:

User Panel Messages

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