← Back to Chapters

Python Scope

? Python Scope

⚡ Quick Overview

In Python, scope is the region of a program where a variable is recognized and can be used. Python follows the LEGB rule to find variables:

L → Local    E → Enclosing    G → Global    B → Built-in

? Key Concepts

  • Local scope – variables created inside a function; accessible only within that function.
  • Enclosing scope – variables in outer functions of nested functions.
  • Global scope – variables defined at the top level of a module or file.
  • Built-in scope – names that are built into Python (like print, len).

When you use a variable name, Python searches in this order: Local → Enclosing → Global → Built-in.

? Syntax and Theory

  • Local variables are created by simple assignments inside a function body.
  • Global variables are declared outside all functions, usually at the top of the file.
  • Enclosing variables live in an outer function when you have nested functions.
  • global keyword allows you to modify a global variable from inside a function.
  • nonlocal keyword allows you to modify a variable from the enclosing (outer) function instead of creating a new local variable.

? Code Examples

? Local Scope

A variable created inside a function belongs to the function’s local scope and cannot be accessed outside.

? View Local Scope Example
def my_func():
    x = 10   # local variable
    print("Inside function:", x)

my_func()
# print(x)  # ❌ Error: x is not defined outside

? Global Scope

A variable created at the top level of the script is global and can be read inside functions.

? View Global Scope Example
x = 100   # global variable

def my_func():
    print("Inside function:", x)

my_func()
print("Outside function:", x)

? Enclosing Scope (Nested Functions)

In nested functions, the inner function can access variables defined in the outer function (enclosing scope).

? View Enclosing Scope Example
def outer():
    y = "outer variable"
    
    def inner():
        print("Accessing:", y)  # enclosing scope
    inner()

outer()

? global Keyword

Use global to modify a global variable from inside a function.

? View global Keyword Example
count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 1

? nonlocal Keyword

Use nonlocal in nested functions when you want to modify a variable from the enclosing function.

? View nonlocal Keyword Example
def outer():
    num = 10   # enclosing variable
    def inner():
        nonlocal num   # modify enclosing variable
        num += 5
        print("Inner:", num)
    inner()
    print("Outer:", num)

outer()

? Live Output and Explanation

? What the Examples Do

  • Local scope example prints Inside function: 10. Trying to use x outside the function raises a NameError.
  • Global scope example prints:
    Inside function: 100 and Outside function: 100.
  • Enclosing scope example lets inner() read y from outer(), printing Accessing: outer variable.
  • global example changes the global count from 0 to 1.
  • nonlocal example changes num in the enclosing function: first prints Inner: 15, then Outer: 15.

? When to Use global vs nonlocal

  • Use global when a truly shared value is needed across the whole module (for example, a basic global counter or configuration flag).
  • Use nonlocal in nested functions, especially in closures, when the inner function should update a value defined in the outer function.
  • Prefer passing parameters and returning values over using global whenever possible.

? Tips and Best Practices

  • Prefer local variables inside functions to avoid unexpected side effects.
  • Use global and nonlocal carefully and only when really needed.
  • Remember that a local variable with the same name as a global one shadows the global inside the function.
  • Keep function scopes small and focused; this makes debugging easier.
  • Always think through the LEGB search order when a variable is not behaving as expected.

? Try It Yourself

  • Create a function with a local variable and try accessing it outside the function. Observe the error and connect it to local scope.
  • Write a nested function where the inner function modifies a variable in the outer function using nonlocal.
  • Use a global variable to keep track of how many times a function has been called.
  • Experiment: remove global from the counter example and see the UnboundLocalError you get.
  • Create your own example that uses all four levels of LEGB (for example, a function that calls print, uses a global name, an enclosing name, and a local name).