Python Forum

Full Version: vars() can't be used in list interpretation?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!
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.
At least I know it's not my fault... thanks!

Indeed, I just replaced all vars() which are causing the error with globals()...
(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