Python Forum
vars() can't be used in list interpretation? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: vars() can't be used in list interpretation? (/thread-34059.html)



vars() can't be used in list interpretation? - Cheng - Jun-22-2021

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!


RE: vars() can't be used in list interpretation? - Yoriz - Jun-22-2021

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.


RE: vars() can't be used in list interpretation? - Cheng - Jun-22-2021

At least I know it's not my fault... thanks!

Indeed, I just replaced all vars() which are causing the error with globals()...


RE: vars() can't be used in list interpretation? - snippsat - Jun-22-2021

(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