Scope resolution via LEGB rule
In Python, the LEGB rule is used to decide the order in which the
namespaces are to be searched for scope resolution.
The scopes are listed below in terms of hierarchy (highest to
lowest/narrowest to broadest):
• Local(L): Defined inside function/class
• Enclosed(E): Defined inside enclosing functions (Nested function
concept)
• Global(G): Defined at the uppermost level
Built-in(B): Reserved names in Python built-in modules
LEGB Scopes of Variables
Local Scope
Local scope refers to variables defined in the current function. Always,
a function will first look up a variable name in its local scope. Only if it
does not find it there, the outer scopes are checked.
Example:
# Local Scope
Example 1: Local Scope
Output:
# Output: Local Scope
Explanation 1
Local and Global Scopes
If a variable is not defined in the local scope, then, it is checked for in
the higher scope, in this case, the global scope.
If you define a variable at the top of your script, it will be a global
variable. This means that it is accessible from anywhere in your script,
including from within a function.
# Global Scope
Example 2: Global Scope
Output:
Output: Global Scope
Explanation 2
Example 2:
Code:
#Global Variable
Example 2: Global Variables
Output:
Output: Global Variables
Explanation 3
Example 3:
Code:
#Global Variable
Example 3: Global Variables
Output:
Output: Global variables
Explanation 4
Local, Enclosed and Global Scopes
For the enclosed scope, we need to define an outer function enclosing
the inner function, comment out the local pi variable of the inner
function and refer to pi using the nonlocal keyword.
# Enclosed Scope
Example: Global and Outer Variables
Output:
Output: Global and Outer Variables
Explanation 5
Local, Enclosed, Global and Built-in Scopes
The final check can be done by importing pi from the math module
and commenting on the global, enclosed, and local pi variables as
shown below:
# Built-in Scope
Example: Built-In Scope of variables
Output:
Output: Built-In Variables
Explanation 6
Conclusion:
In the above article, we have seen the LEGB rule where L stand for
Local, E stands for enclosed, G for Global and B for Built-In scopes of a
variable. Python searches namespaces in LEGB in order to determine
the value of an object given its name.
We can create different levels of Scopes of variables that depend upon
the block where it is been defined. These are created within functions,
classes and modules. In case we define the object with the same name
in different level of scopes, they are treated differently and are isolated.
The value of the name will be the value of the object in scope. When we
modify an object by that name, it will only affect the object in scope.
We can overrule and avoid this rule by using the scope of a name with
keywords global and nonlocal also whereas it is a bad practice and
suggested to use occasionally.