Python Scope and the LEGB Rule: Local, Enclosing, Global, Built-in

Python scope is the set of rules Python uses to decide where a name like count or print comes from. The LEGB rule means Python looks for a name in the Local, Enclosing, Global, and Built-in scopes, in that order. This article shows how that search works, why UnboundLocalError happens, and how global and nonlocal change name lookup.

Difficulty: Beginner

Helpful to know first: basic Python variables, functions, and how to read simple code blocks.

How Python Finds a Name with the LEGB Rule

When Python sees a name in your code, it does not guess. It follows a clear search order called LEGB: Local, then Enclosing, then Global, then Built-in. The first matching name wins.

That means the same spelling can refer to different values in different places. A variable inside a function can hide a variable with the same name outside the function. A nested function can also use names from the function that contains it.

Python
x = 10

def show():
    print(x)

show()
# Output: 10

Here, x is not found inside show(), so Python looks in the global scope and finds 10. If no global name existed, Python would keep looking in built-ins only for names like print or len.

Local Scope: Names Created Inside a Function

A local name belongs to the current function call. It usually exists only while that function runs. This is the most common scope beginners use.

Python
def greet():
    message = "Hello, world!"
    print(message)

greet()
# Output: Hello, world!

Inside greet(), the name message is local. Outside the function, that name does not exist anymore.

Python
def greet():
    message = "Hello"

greet()
print(message)
# NameError: name 'message' is not defined

Python cannot find message in the global scope, and there is no enclosing scope here either, so it raises NameError.

Enclosing Scope: How Nested Functions See Outer Variables

An enclosing scope is the function that wraps another function. This matters when you define a function inside another function. The inner function can read names from the outer function even after the outer function has started running.

Python
def outer():
    message = "Hello from outer"

    def inner():
        print(message)

    inner()

outer()
# Output: Hello from outer

Here, message is not local to inner(). Python finds it in the enclosing function outer(). This is the basis of closures.

Closures keep access to enclosing names

A closure is a function that remembers names from an enclosing scope even after the outer function has finished. This is common in callbacks, decorators, and function factories.

Python
def make_greeter(name):
    def greeter():
        print(f"Hello, {name}!")

    return greeter

say_hello = make_greeter("Ada")
say_hello()
# Output: Hello, Ada!

The inner function uses name from the enclosing function. Even though make_greeter() has already returned, the name is still available to the returned function.

Global Scope: Names Defined at the Top Level

A global name is defined at the top level of a module. Functions can read global names unless they create a local name with the same spelling.

Python
school = "DevDocs High"

def show_school():
    print(school)

show_school()
# Output: DevDocs High

Reading a global name is allowed. The problem starts when you try to assign to that same name inside the function.

Why assigning inside a function changes the search path

Python decides whether a name is local at compile time. If a function contains an assignment to a name anywhere in its body, Python treats that name as local in that function unless you declare it with global or nonlocal.

Python
count = 10

def show_count():
    print(count)
    count = 11

show_count()
# UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

Python sees the assignment to count and marks it as local. Then the print() tries to read that local variable before it has a value, so you get UnboundLocalError.

Built-in Scope: Names Python Provides for You

The built-in scope contains names that Python makes available automatically, such as print, len, range, and Exception. If Python cannot find a name in local, enclosing, or global scope, it looks here next.

Python
print(len([1, 2, 3]))
# Output: 3

If you create your own global name with the same spelling as a built-in, the global name hides the built-in inside that module.

Python
len = 99

print(len)
# Output: 99

That does not remove the real built-in len(). It only makes the name len in this module refer to the integer 99.

Avoid naming your own variables after built-ins. It makes code harder to read and can break later calls to the built-in function in the same scope.

How global Lets a Function Rebind a Module Name

Use global when a function needs to reassign a module-level name. It tells Python to use the global variable instead of creating a new local one.

Python
total = 0

def add_one():
    global total
    total = total + 1

add_one()
print(total)
# Output: 1

Without global, the assignment would create a local variable and fail if you tried to read total first.

Use global carefully. It makes code harder to reason about because a function now depends on and changes state outside itself. For small scripts it can be fine, but for larger programs it is often better to return a value instead of mutating a global name.

How nonlocal Lets an Inner Function Rebind an Enclosing Name

Use nonlocal inside a nested function when you want to reassign a variable from the nearest enclosing function, not from the global scope.

Python
def make_counter():
    count = 0

    def increment():
        nonlocal count
        count = count + 1
        print(count)

    return increment

counter = make_counter()
counter()
counter()
# Output:
# 1
# 2

Here, count belongs to the enclosing function make_counter(). The nonlocal statement tells Python not to create a new local count inside increment().

What Happens When Names Shadow Each Other

Shadowing means one name hides another name with the same spelling. This is common and often confusing when learning scope. The closest name in the LEGB order wins, even if an outer name has the same spelling.

Python
value = "global"

def outer():
    value = "enclosing"

    def inner():
        value = "local"
        print(value)

    inner()

outer()
print(value)
# Output:
# local
# global

The inner function uses its own local value. The global value is unchanged. The enclosing value is also hidden by the local one inside inner().

How Scope Really Behaves in Python

Python scope is determined by how a name is used, not just where the code appears. If a function assigns to a name anywhere inside the function body, Python treats that name as local throughout that function body unless you declare it global or nonlocal. That is why reading a variable before assigning to it can raise UnboundLocalError.

This rule often surprises beginners because they expect Python to read the outer value first and only treat the assignment as a later change. Python does not work that way. The compiler decides scope before the function runs.

Another important detail is that scope is about names, not objects. A list in global scope can be mutated inside a function without global, because mutating an object is not the same as rebinding the name. Rebinding means making the name point to a different object.

Python
items = []

def add_item():
    items.append("book")

add_item()
print(items)
# Output: ['book']

Here, the function does not rebind items; it changes the list object that items already refers to. That is why no global statement is needed.

Predict the Output

Read each snippet carefully and decide what it prints. These examples target the most common mistakes with local, global, and enclosing scope.

Reading a name before assigning to it

What does this print?

Python
x = 5

def demo():
    print(x)
    x = 6

demo()
Show answer

It raises UnboundLocalError, not 5. The assignment to x inside demo() makes x a local name for the whole function. When print(x) runs, the local variable has not been assigned yet.

Terminal
# UnboundLocalError: cannot access local variable 'x' where it is not associated with a value

Closure with an enclosing name

What does this print?

Python
def outer():
    text = "outer"

    def inner():
        print(text)

    inner()

outer()
Show answer

It prints outer. The inner function does not have a local text, so Python looks in the enclosing scope and finds the value from outer().

Terminal
# Output: outer

Common Mistakes with Python Scope

Assuming assignment uses the outer variable first

Many beginners think Python will print the global value and then update it. Instead, any assignment inside the function makes the name local unless you declare otherwise.

Problem: The function tries to read count before assigning to it, but Python already treats count as a local name because of the assignment later in the function.

Python
count = 3

def show():
    print(count)
    count = 4

show()

Fix: If the function should use the module-level variable, declare it with global. If it should be independent, use a different local name.

Python
count = 3

def show():
    global count
    print(count)
    count = 4

show()

The fixed version works because global tells Python to use the module name instead of creating a local one.

Using nonlocal when there is no enclosing binding

nonlocal only works for names in an enclosing function, not for module-level names and not for names that do not exist outside the inner function.

Problem: This function says nonlocal for score, but there is no enclosing function that defines score.

Python
def play():
    nonlocal score
    score = 1

Fix: Define score in an outer function, or use global if you truly want module-level state.

Python
def game():
    score = 0

    def play():
        nonlocal score
        score = 1

    play()
    print(score)

game()

The corrected version works because score now exists in an enclosing function scope.

Shadowing a built-in name

Using a built-in name for your own variable can hide the real function. This often causes confusing errors later.

Problem: The name list now refers to a string, so calling list() no longer works in this scope.

Python
list = "items"
print(list([1, 2]))

Fix: Rename the variable so the built-in stays available.

Python
item_label = "items"
print(list([1, 2]))
# Output: [1, 2]

The corrected version works because the built-in list() is no longer hidden.

Find the Bug

One line in this counter looks right, but it breaks the scope rules. Find the bug before you read the answer.

Python
def make_counter():
    count = 0

    def increment():
        count = count + 1
        return count

    return increment
Show answer

The bug is that increment() assigns to count without declaring nonlocal. That makes count local to increment(), so the right-hand side tries to read a local variable before it has a value.

Fixed code:

Python
def make_counter():
    count = 0

    def increment():
        nonlocal count
        count = count + 1
        return count

    return increment

The fixed version works because the inner function now updates the enclosing variable instead of creating a new local one.

When to Use Local, Global, or Enclosing Names

Most functions should use local names. That keeps state inside the function and makes the code easier to test and reuse. Use enclosing names when you are building closures and need an inner function to remember state. Use global only when a function truly needs to rebind module-level state.

ChoiceUse it whenTypical result
LocalThe value belongs to one function callSafer, easier to follow
EnclosingAn inner function needs values from an outer functionUseful for closures
GlobalSeveral functions must share one module-level nameWorks, but harder to manage

In practice, many programs can avoid global by passing values as arguments and returning results. That usually makes dependencies clearer than hidden shared state.

Scope vs mutation

Beginners often mix up rebinding and mutation. Rebinding means changing which object a name points to. Mutation means changing the object itself.

Python
numbers = []

def append_number():
    numbers.append(1)

append_number()
print(numbers)
# Output: [1]

The function mutates the list. It does not assign a new object to numbers, so no scope declaration is required.

Interview Questions About Python Scope

Why does Python raise UnboundLocalError instead of NameError?

UnboundLocalError means Python found the name in the function’s local scope rules, but the local variable was not assigned a value yet. NameError means Python could not find the name in any scope at all.

Why can a function read a global variable without declaring it global?

Reading is allowed because Python only needs to look up the value. The global statement is needed when the function wants to rebind the module-level name.

What is the difference between global and nonlocal?

global refers to a module-level name. nonlocal refers to a name in the nearest enclosing function scope. They solve different rebinding problems.

Try It Yourself

Write a function-based temperature tracker that uses scope correctly.

  • Create a function named make_tracker().
  • Inside it, define a local variable total starting at 0.
  • Inside it, define an inner function record(value) that adds value to total using nonlocal.
  • Make record() print the new total each time it runs.
  • Return record from make_tracker().
  • Call the returned function with 10 and then -3.

Expected output:

Python
10
7

Hint: The inner function must change the variable from the outer function, not create a new local one.

Show solution
Python
def make_tracker():
    total = 0

    def record(value):
        nonlocal total
        total = total + value
        print(total)

    return record

tracker = make_tracker()
tracker(10)
tracker(-3)

Summary

  • Python resolves names in this order: local, enclosing, global, built-in.
  • Assignment inside a function makes that name local unless you use global or nonlocal.
  • UnboundLocalError usually means Python treated a name as local, but you read it before assigning to it.
  • Closures let inner functions use names from enclosing functions even after the outer function has returned.
  • global rebinding should be used sparingly; local values and function returns are usually clearer.
  • Mutating an object is not the same as rebinding its name.

Next, learn about Python closures and how they keep state without using global variables.