When I run this code:
a = '1'
vars()['a'] = '2'
print a
I get the following output:
2
But when I run this code:
def bar():
a = '1'
vars()['a'] = '2'
print a
bar()
I get the following output:
1
Now my question is: why is this happening and how can I make the second case, give me the same solution as the first case.
Edit:
Could not find a solution, but I found a small hack around it ... Although I will not use exec:
def bar():
a = "a"
b = "b"
exec a+"="+b
print a
bar()
Which gives me the result:
b
If someone can find a better solution, then it would be great. I don't set any global variables this way or do anything crazy, so don't worry about that.
source
share