The variable names in Python are parsed at compile time, in other words, at compile time (that is, when the interactive console enters the code or import file), Python has decided whether a variable should be a local variable or a global variable. Take a look at the following example:
>>>x = 99>>>def Test (): print(X)>>>Test () 99
The variable referenced in the function test, according to the scope chain lookup rule (LEGB rule), finds the value of the global variable X.
>>>x = 99>>>def Test (): print(X) = 88>>> 'X' referenced before assignment # error
According to the beginning of the article, Python determines whether a variable is local, or global, at compile time, when compiled to the function test, see the assignment of x = 88, so Python thinks that x in the function test should be a local variable, so when the test function is running, Executes the print (X) statement, finds that the local variable X is not assigned to the reference, so the error.
In fact, any assignment performed within the function body, including =,import, nested DEF definitions, nested class definitions, and so on, will produce local variables. Inside a python function, local variables and global variables cannot coexist, only one can exist:
>>>x = 99>>>def Test (): = X>>> Test ()>>>x # output is88
In the example above, Python, when compiling the function test, first sees the assignment statement x = 88, which determines that x should be a local variable, but when it continues down, it finds the Global X statement, which declares X as a local variable, so Python eventually determines the x variable inside the test function as a global variable, and eventually runs, changes the value of the global variable x, and finally prints the result to 88.
It should be noted that if the global declaration is later than the use of the variable, Python will produce a warning: syntaxwarning:name ' X ' is assign to before global declaration
Python determines whether a variable is local, or global, at compile time.