Reputation:
I am generating variables through a list and a class. All that works fine. outside a function i can call the data one of these variables hold, but inside a function i can call the data directly, but not using the vars()[] method
I have tried to search for a direct answer on google and this site, but i have been unable to find a solution.
what can i do to make the:
print(str(k)+" :"+str(vars()[k].data))
inside runner() work?
class LED:
def __init__(self, gpio):
self.gpio = gpio
self.data = []
self.state = False
LED_list = {'G1':8}
for k,v in LED_list.items():
vars()[k] = LED(v)
G1.data = [10,15,20,25]
print("outside")
for k,v in LED_list.items():
print(str(k)+" :"+str(vars()[k].data))
def runner():
print("inside")
for k,v in LED_list.items():
print(k,v)
print("G1 data: "+str(G1.data))
print(str(k)+" :"+str(vars()[k].data))
runner()
This is my output:
outside
G1 :[10, 15, 20, 25]
inside
G1 8
G1 data: [10, 15, 20, 25]
Traceback (most recent call last):
File "/.../Main2.py", line 23, in <module>
runner()
File "/.../Main2.py", line 21, in runner
print(str(k)+" :"+str(vars()[k].data))
KeyError: 'G1'
Upvotes: 1
Views: 873
Reputation:
globals()
works instead of vars()
- but read the notes under, because it is not the correct solution to the problem to use vars()
and globals()
.
class LED:
def __init__(self, gpio):
self.gpio = gpio
self.data = []
self.state = False
LED_list = {'G1':8}
for k,v in LED_list.items():
vars()[k] = LED(v)
G1.data = [10,15,20,25]
print("outside")
for k,v in LED_list.items():
print(str(k)+" :"+str(vars()[k].data))
def runner():
print("inside")
for k,v in LED_list.items():
print(k,v)
print("G1 data: "+str(G1.data))
print(str(k)+" :"+str(globals()[k].data))
runner()
Upvotes: 1