Scope of Variable and LEGB Rule


☞Part(s) of a program within which a name is legal and accessible is called scope of the name.

☞Scope of variables can be resolved using the LEGB rule.

LEGB rule :

☞LEGB stands for Local, Enclosing, Global, and Built-in, which are four different scopes in which variables can be defined.

☞The scope defines where a variable can be accessed and how it interacts with other variables of the same name but different scopes.

1. Local (L):

☞Variables defined within a function or block of code have local scope.

☞They are accessible only within that specific function or block and cannot be accessed outside of it.

2. Enclosing (E):

☞This refers to variables in the enclosing function's scope if the current code is inside a nested function.

☞ If there are nested functions, each nested function can access variables from its containing function, but not vice versa.

3. Global (G):

☞Variables defined at the top level of a script or module have global scope.

☞They are accessible from anywhere in the script, including within functions.

☞However, to modify a global variable inside a function, you need to declare it as "global" inside that function.

4. Built-in (B):

☞These are the predefined names and functions that are available in the programming language itself.

☞Examples include built-in functions like `print()`, `len()`, and constants like `True` and `False`.

Example :

 
# Global scope
global_var = "I am global"

def outer_function():
    outer_var = "I am enclosing"

    def inner_function():
        inner_var = "I am local"
        print(inner_var)   # Accessing local variable
        print(outer_var)   # Accessing enclosing variable
        print(global_var)  # Accessing global variable

    inner_function()

outer_function()
print(global_var)  # Still accessible outside the functions

Output :

 
I am local
I am enclosing
I am global
I am global