EDIT: This question is NOT ANSWERED BY THE LINKS ABOVE that a mod added. As I said before in a comment, Python 3 brought changes, and the examples given in those answers were for Python 2. If I compile those in my Python 3 environment, I get the same error as here.
Consider
str = "x = [113, 223]"
exec(str)
print(x[0]) #113
This works perfectly. But if I want this code to be executed in a function, it returns an error NameError: name 'x' is not defined
. Here's a minimal working example:
def some_code():
str = "x = [1, 2]"
exec(str)
print(x)
some_code()
What is going on here?
I need a solution to
use exec inside the function (because ultimately its a tkinter function -see the first edit history of this question- and I'm reading this from a file that should be executed
I would like to easily be able to refer to x, because I will need to do that in a lot of places. So using a long line of code to refer to x will be cumbersome.