I want to select a variable by using another variable. In C I would store the address of the selected variable in a pointer. If I now want to read the variable I use this pointer. But in python there are no pointers. So I did it by using eval. The set function is called first and after some time the get function is called. The get function should return the same as long as the selection stays the same.
See the example. Is there a better way?
sel = 0
a = 1
b = 2
def set(index):
if index == 0:
sel = 'a'
elif index == 1:
sel = 'b'
return sel
def get(sel):
global a, b
return eval(sel)
sel = set(0)
print(get(sel))
a = 3
print(get(sel))
sel = set(1)
print(get(sel))
The result should be:
1
3
2