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
#2
list comprehensions have their own scope in python 3
https://bugs.python.org/issue3692

It doesn't look great, there is probably a better way to achieve whatever it is you are trying to achive.
Cheng likes this post
Reply
#3
At least I know it's not my fault... thanks!

Indeed, I just replaced all vars() which are causing the error with globals()...
Reply
#4
(Jun-22-2021, 10:38 AM)Cheng Wrote: I am using vars() and globals(). I am not sure whether this is a good practice, do let me know if it isn't!
It's a bad practice🚽
If demystify it so is globals() a internal dictionary that Python use.
It's much cleared for everyone if make a ordinary dictionary that is visible.
my_dict = {'x': 10, 'y': 5}
>>> my_dict['x']
10
>>>
>>> my_dict.keys()
dict_keys(['x', 'y'])
>>>
>>> my_dict.values()
dict_values([10, 5])
>>>
>>> for key, value in my_dict.items():
...     print(f'{key} = {value}')
...     
x = 10
y = 5
If think about so have we done code under with a visible my dict,then there is no need to call globals().
x = 10
y = 5
buran and Cheng like this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  This is an Object - Code interpretation JoeDainton123 2 1,804 Jun-16-2021, 08:11 PM
Last Post: snippsat
  English interpretation of the following file handing snippet mortch 5 3,177 May-30-2019, 08:10 AM
Last Post: mortch
  using vars from one file to match lines in another gt76_noobster 3 2,613 Jan-30-2019, 05:34 PM
Last Post: ichabod801
  Vars and getattr problem catosp 5 4,040 Aug-28-2018, 02:54 PM
Last Post: buran
  A help whit vars and strings dhoyosg 10 5,320 May-05-2018, 08:52 AM
Last Post: dhoyosg
  Interpretation of a code Alberto 1 2,101 Jan-02-2018, 06:46 PM
Last Post: Windspar
  What should I name these vars RickyWilson 1 2,207 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