Scope Resolution Via LEGB Rule
Scope Resolution Via LEGB Rule
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
Output:
Explanation 1
# Global Scope
Output:
Explanation 2
Example 2:
Code:
#Global Variable
Example 2: Global Variables
Output:
Explanation 3
Example 3:
Code:
#Global Variable
Example 3: Global Variables
Output:
Explanation 4
# Enclosed Scope
Example: Global and Outer Variables
Output:
Explanation 5
# Built-in Scope
Example: Built-In Scope of variables
Output:
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.