1 Scope of variables
Python is a static scope, meaning that in Python, the scope of a variable derives from its position in the code, and there may be different namespaces in different locations. Namespaces are the embodiment of variable scopes.
2 LEGB meaning of the respective representatives
2.1 l-local
namespace within the function. Scope: The current entire function body range.
2.2 e-enclosing Function locals
The namespace of the outer nested function. Scope: Closure function.
2.3 G-global
The global namespace. Scope: Current module (file).
2.4 B-builtin
Built-in module namespaces. Scope: All modules (Files).
Note: There is no block-level scope in Python. Block-level scope, a variable in a code block, such as the IF and for post code.
3 LEGB Rules
The LEGB rule is to look for variables in l->e->g->b order. In other words, when a variable with the same variable name is found in a different namespace, we first look for the local variable, and if it is not found, then look for the global variable.
4 common variable types based on namespaces
4.1 Local Variables
A variable that is defined inside a function. Scope is inside the function. View Local Variables command: Locals ().
4.2 Global Variables
Outside the function, variables defined at the outermost of the file. Scope is internal to the entire file. View Global Variables Command: Globals ()
4.3 note
Variable access principle: from inside to outside. When the names of global variables and local variables are identical, the nearest principle is adopted.
4 Case explanation
The 4.1 code is as follows
1A ="G Global" #defines a global variable A and assigns "G global" to a2 defmyfunc ():3A ="e Local 1" #A local variable A is defined, and the "E Local 1" is assigned to a4 5 definner ():6A ="L Partial 2" #A local variable A is defined, and the "E Local 1" is assigned to a7 Print("Inner printed A:", a)8 Inner ()9 Print("MyFunc printed A:", a)Ten One A MyFunc () - Print("__main__ printed A:"A
4.2 Code Execution Results
4.3 Code results analysis
python--LEGB rules for scopes