Scope

Scope in Python

In Python, scope determines where a variable can be accessed or modified. Scope follows the LEGB Rule, which stands for:

Local → Enclosing → Global → Built-in

When Python encounters a variable, it searches in this order:

  1. Local — inside the current function
  2. Enclosing — in any outer functions
  3. Global — at the top level of the script/module
  4. Built-in — names like len(), sum(), etc.

Global Scope

A variable defined outside of all functions is in the global scope. It can be accessed inside functions but cannot be changed unless explicitly declared as global.

var1 = "I am global"

def my_func():
    print(var1)  # Can access global variable

Modifying a global variable inside a function:

var1 = 5

def change_var():
    global var1
    var1 = 10  # Modifies global var1

change_var()
print(var1)  # Output: 10

Local Scope

A variable defined inside a function is local to that function. It only exists during the function's execution.

def my_func():
    local_var = "I'm local"
    print(local_var)

my_func()
print(local_var) # Error: local_var is not defined outside

Enclosing Scope

Also called Nonlocal scope, this applies to nested functions. Variables defined in the outer (enclosing) function are accessible to inner functions, but are not global.

def outer():
    msg = "outer value"

    def inner():
        print(msg)  # Accesses enclosing variable

    inner()

outer()

Using Nonlocal to Modify Enclosing Variables

If you want to modify a variable in the enclosing (non-global) scope from a nested function, use nonlocal.

def outer():
    count = 0

    def inner():
        nonlocal count
        count += 1
        print("Count:", count)

    inner()
    inner()

outer()

Example: All in One

var = "global"

def outer():
    var = "enclosing"
    
    def inner():
        nonlocal var
        var = "modified enclosing"
        print("Inner:", var)
    
    inner()
    print("Outer:", var)

outer()
print("Global:", var)