I think that below code fully describes the problem. Why in the Test2 function x has not been defined? Why the Test3 function does not return an error?
>>> def Test1():
exec('x=2')
print(str(x))
>>> Test1()
2
>>> def Test2():
global x
exec('x=2')
print(str(x))
>>> Test2()
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
Test2()
File "<pyshell#38>", line 4, in Test2
print(str(x))
NameError: global name 'x' is not defined
>>> def Test3():
global x
x=2
print(str(x))
>>> Test3()
2
The answer given by @SanSS is correct, as is the comment by @Colin Dunklau, but I wanted to add a bit more info. One thing that may trip you up is that the
global xin Test2 does not carry through to the exec-ed code. So the exec creates a local variablex, while theprint xtries to read a global variable. These two examples may be helpful. . .Here by passing one dict, you tell exec to use that as globals and locals, so the exec assigns to globals:
Here by including the global declaration in the exec-ed code, you make the exec assign to the global, which the print statement then reads:
To reiterate, however, it’s usually not a good idea to use
exec. It can be good to play around with stuff like this sometimes just to understand how Python works, but there are few cases where this is a good way to actually accomplish something with your code.