Scope of Variables in Python

Scope of Variables in Python

Scope of variables essentially means where a variable is accessible within the code. There are four primary scopes in Python, often summarized by the acronym LEGB.

  1. Local (L): Variables that are defined inside the function have local scope. They are accessible only inside the function not outside the function. When the function ends, local variables are discarded.
def my_function():
    x = 10  # Local variable
    print(x)

my_function()  # Output: 10
print(x)       # Error: x is not defined outside the function
  1. Enclosing (E): This scope is for variables in nested functions. When a function is defined within another, the inner function can access the variables of outer function. We use nonlocal keyword to modify enclosing variable inside the inner function.
def outer_function():
    x = 10  # Enclosing variable

    def inner_function():
        nonlocal x
        print(x)   # Accesses 'x' from the enclosing scope, output: 10
        x = 30
        print(x)  # Modify 'x', Output: 30

    inner_function()
outer_function()
  1. Global (G): Variables defined at the top of the script or module are in the global scope. They can be accessible anywhere in the module including inside the function (unless the local variable is created with the same name). We use global keyword to modify the global variable inside the function.
x = 20  # global variable
def my_function():
    global x 
    x = 40
    print(x)
my_function()  # output: 40
  1. Built-In (B): These are special name that are part of Python’s built-in functions and exceptions. They are always available, and we generally don’t modify them. Examples are like, len(), range(), etc.

Example of LEGB Rule

x = 10  # global scope

def outer_function():
    x = 20  # Enclosing scope

    def inner_function():
        x = 30  # Local scope
        print(X)  # Local x, output: 30

    inner_function()
    print(x)  # Enclosing x, output: 20

outer_function()
print(x)  # Global x, output: 10

In this example, python uses LEGB rule to determine which x to access in which part of the code. The order python follows is Local → Enclosing → Global → Built-In.