Written by
on
on
Python variable scopes explained
In Python, understanding variable scope is crucial for writing clean and effective code. The scope of a variable determines where it can be accessed and modified within your program. Python uses a hierarchical rule known as LEGB, which stands for Local, Enclosing, Global, and Built-in scopes. Each of these levels has its own significance, dictating how Python resolves variable names. Check out the code below. Do you know what will be printed out? If you are unsure see the explanation below.
- Variables defined (having a value assigned: x = 10) within a function have local scope. They are not accessible outside the function.
- Having a variable defined in the global scope can be accessed from the function but if the functions try to assign a value to it then it becomes local.
- If a function tries to access the variables of an enclosing function than the variable has to be declared to be nonlocal in the inner method.
- Note that variables declared global cannot be refered from an innerscope with the nonlocal declaration.
- If a method tries to access a global variable then variable has to be declared global in the method.
- The nonlocal keyword declares that the variable refers to a variable defined in an outer function scope. Nonlocal declarations can be chained together so, that the most-inner function refers to an inner function’s variable that refers to an outer functions variable.
- If the outer function’s variable is declared as global, then the interpreter throws an error because there is no variable defined in the outer function scope. Therefore the inner scopes cannot refer to i. Nonlocal declarations can be chained together so, that the most-inner function refers to an inner function’s variable that refers to an outer functions variable.
And the output of the code is the following.
Layer 4 x: 4
Layer 3 x: 4
Layer 2 x: 2
Layer 1 x: 2
Global x: 100