Skip to content
Python

Python Variable Scope: LEGB, global and nonlocal

Ihsan Ullah · 13 min read
Python variable scope, Lesson 24 of the Python course: the LEGB rule, global and nonlocal

Python course · Module 5: Functions · Lesson 24 of 63

Quick answer: Scope is the part of a program where a name can be seen. A variable you create inside a function is local: it exists only while the function runs. A variable created at the top of the file is global: functions can read it, but they cannot assign a new value to it unless you write global name. Python looks up a name in four places, in this order: Local, Enclosing function, Global, Built-in. This is the LEGB rule.

In this lesson you will learn:

  • what local and global variables are, and why a local name disappears after the function ends
  • how the LEGB rule decides which variable Python uses
  • why UnboundLocalError happens and how to fix it
  • how global and nonlocal work, and what a closure is
  • why you should avoid global variables

Before you start: finish Lesson 23, Python Function Arguments: Defaults, Keyword Arguments, *args and **kwargs. You need def, parameters and return from Lesson 22. All examples were tested on Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org.

Local variables live inside the function

Every function call gets its own private space for names. Our running example is a small shop checkout:

def checkout(price):
    delivery = 150
    total = price + delivery
    return total

print(checkout(450))
print(delivery)
600
Traceback (most recent call last):
  File "/home/learner/python-course/err1_local_outside.py", line 7, in <module>
    print(delivery)
          ^^^^^^^^
NameError: name 'delivery' is not defined

The call printed 600. But delivery, total and the parameter price are local to checkout(): they are created when the function starts and thrown away when it returns. Outside, delivery does not exist, so Python raises NameError. The Python tutorial says that “all variable assignments in a function store the value in the local symbol table”. If you need a value outside the function, return it.

Global variables can be read inside a function

A variable assigned at the top level of the file, outside every function, is global. Any function in the file can read it:

delivery = 150

def checkout(price):
    return price + delivery

print(checkout(450))
print(checkout(60))
600
210

checkout() has no local delivery, so Python looks outside the function and finds the global one.

The same name inside and outside

Now assign delivery inside the function too:

delivery = 150

def checkout(price):
    delivery = 0
    print("Inside, delivery is", delivery)
    return price + delivery

print(checkout(450))
print("Outside, delivery is", delivery)
Inside, delivery is 0
450
Outside, delivery is 150

These are two different variables with the same name. The assignment delivery = 0 created a new local variable. It hides the global one inside the function, and the global delivery stays 150. The tutorial’s section on scopes calls this a “special quirk of Python”: unless you use global or nonlocal, “assignments to names always go into the innermost scope”.

The LEGB rule

When Python meets a name, it searches four scopes, from the inside out, and uses the first match:

  1. L, Local: names assigned inside the current function.
  2. E, Enclosing: names in any function that contains this function (when you write a def inside another def).
  3. G, Global: names assigned at the top level of the file.
  4. B, Built-in: names Python always has, like print, len and sum.

The same section of the tutorial lists this order: the local names are searched first, then enclosing functions, then “the current module’s global names”, and last “the namespace containing built-in names”.

Python variable scope LEGB diagram from Lesson 24: nested Local, Enclosing, Global and Built-in scopes, searched from the inside out.
Python looks for a name in the Local scope first, then in Enclosing functions, then in the Global scope of the file, and last in the Built-in names. The first match wins.

Here all four scopes have a label:

label = "global"

def outer():
    label = "enclosing"

    def inner():
        label = "local"
        print("inner sees:", label)

    inner()
    print("outer sees:", label)

outer()
print("module sees:", label)
print("len is built in:", len("Pen"))
inner sees: local
outer sees: enclosing
module sees: global
len is built in: 3

Each function sees its own label first. Now remove the local assignments and watch Python search outwards:

label = "global"

def outer():
    label = "enclosing"

    def inner():
        print("inner sees:", label)

    inner()

def other():
    print("other sees:", label)

outer()
other()
inner sees: enclosing
other sees: global

inner() has no local label, so it uses the enclosing one from outer(). other() is not inside outer(), so it skips straight to the global label.

Built-ins come last, so your own names can hide them:

len = 5
print(len("Notebook"))
Traceback (most recent call last):
  File "/home/learner/python-course/err2_shadow_builtin.py", line 2, in <module>
    print(len("Notebook"))
          ~~~^^^^^^^^^^^^
TypeError: 'int' object is not callable

The global len (the number 5) is found before the built-in len(), and a number cannot be called. This is why Lesson 5 warned against names like list and input.

if blocks and for loops do not make a scope

Functions and comprehensions create a new scope, but if blocks and for loops do not. A variable made inside an if block or a for loop (Lesson 11 and Lesson 12) is still there after the block:

for item in ["Pen", "Notebook", "Ruler"]:
    pass
print("After the loop, item is", item)

if True:
    message = "made inside an if block"
print(message)
After the loop, item is Ruler
made inside an if block

A comprehension from Lesson 21 is different. Its loop variable stays inside it:

doubled = [cost * 2 for cost in [60, 40]]
print(doubled)
print(cost)
[120, 80]
Traceback (most recent call last):
  File "/home/learner/python-course/err3_comprehension_variable.py", line 3, in <module>
    print(cost)
          ^^^^
NameError: name 'cost' is not defined

UnboundLocalError: a local variable with no value yet

This function reads the global stock, then tries to change it:

stock = 12

def sell_one():
    print("Stock before:", stock)
    stock = stock - 1
    return stock

sell_one()
Traceback (most recent call last):
  File "/home/learner/python-course/err4_unbound.py", line 8, in <module>
    sell_one()
    ~~~~~~~~^^
  File "/home/learner/python-course/err4_unbound.py", line 4, in sell_one
    print("Stock before:", stock)
                           ^^^^^
UnboundLocalError: cannot access local variable 'stock' where it is not associated with a value

The error points at the print() on line 4, not at the line that changes stock. Python decides which names are local before the function runs. Line 5 assigns to stock, so stock is local in the whole of sell_one(), and at line 4 it has no value yet. The execution model explains: “If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block.” The short form stock -= 1 fails in exactly the same way.

The best fix is to pass the value in and return the new value:

stock = 12

def sell_one(current):
    return current - 1

stock = sell_one(stock)
stock = sell_one(stock)
print("Stock now:", stock)
Stock now: 10

Now the function only uses its parameter, and the caller decides what to do with the result.

The global keyword

If you really want a function to change a global variable, declare it with global at the top of the function:

stock = 12

def sell_one():
    global stock
    stock = stock - 1

sell_one()
sell_one()
print("Stock now:", stock)
Stock now: 10

global stock tells Python that stock here means the global variable, so the assignment changes it. The global line must come before any use of the name, or the program does not even start:

stock = 12

def sell_one():
    print(stock)
    global stock
    stock = stock - 1

sell_one()
  File "/home/learner/python-course/err5_global_after_use.py", line 5
    global stock
    ^^^^^^^^^^^^
SyntaxError: name 'stock' is used prior to global declaration

Changing a list does not need global

global is only needed to assign a name. Calling a method that changes a list, like append() from Lesson 15, is not an assignment:

cart = []

def add_item(name):
    cart.append(name)

add_item("Pen")
add_item("Notebook")
print(cart)
['Pen', 'Notebook']

The function reads the name cart (found in the global scope) and changes the list it points to. But write cart = cart + [name] and cart becomes local again:

cart = []

def add_item(name):
    cart = cart + [name]

add_item("Pen")
Traceback (most recent call last):
  File "/home/learner/python-course/err6_list_plus_assign.py", line 6, in <module>
    add_item("Pen")
    ~~~~~~~~^^^^^^^
  File "/home/learner/python-course/err6_list_plus_assign.py", line 4, in add_item
    cart = cart + [name]
           ^^^^
UnboundLocalError: cannot access local variable 'cart' where it is not associated with a value

nonlocal and closures

nonlocal is like global, but for the enclosing function, the E in LEGB. It lets an inner function change a variable of the function around it. Here make_counter() builds a ticket machine:

def make_counter():
    count = 0

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

    return next_ticket

ticket = make_counter()
print(ticket())
print(ticket())
print(ticket())

other_queue = make_counter()
print(other_queue())
1
2
3
1

make_counter() returns the inner function itself, without calling it (no brackets after next_ticket). make_counter() has finished, yet ticket() still remembers count. An inner function that remembers variables from its enclosing function is called a closure. Each call of make_counter() makes a new count, so other_queue starts again at 1. Closures come back in Lesson 46, Closures and Decorators.

Without nonlocal, the assignment makes count local to next_ticket(), and you get the same error as before:

def make_counter():
    count = 0

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

    return next_ticket

ticket = make_counter()
print(ticket())
Traceback (most recent call last):
  File "/home/learner/python-course/err7_counter_without_nonlocal.py", line 11, in <module>
    print(ticket())
          ~~~~~~^^
  File "/home/learner/python-course/err7_counter_without_nonlocal.py", line 5, in next_ticket
    count = count + 1
            ^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

Why to avoid global variables

global works, but it makes programs hard to follow. Here a bill total is kept in a global:

total = 0

def add_to_bill(price):
    global total
    total = total + price

add_to_bill(450)
add_to_bill(60)
print("Customer 1 pays", total)

add_to_bill(3200)
print("Customer 2 pays", total)
Customer 1 pays 510
Customer 2 pays 3710

Customer 2 bought one backpack for 3200, but the bill says 3710, because nobody reset total. Any function can change a global, so when its value is wrong, you must check every function. The programming FAQ says that requiring global for assignments “provides a bar against unintended side-effects”. The same task with a parameter and return has no hidden state:

def bill(prices):
    total = 0
    for price in prices:
        total = total + price
    return total

print("Customer 1 pays", bill([450, 60]))
print("Customer 2 pays", bill([3200]))
Customer 1 pays 510
Customer 2 pays 3200

Each call starts from total = 0, so the result depends only on what you pass in. Global constants, values you never change, are fine. PEP 8 says constants “are usually defined on a module level and written in all capital letters”, for example DELIVERY_FEE = 150.

Try it yourself

Exercise 1: Predict the output

Before you run it, write down what this code prints. Then run it and check.

price = 100

def apply_offer():
    price = 80
    print("Inside:", price)

apply_offer()
print("Outside:", price)

Exercise 2: Fix the UnboundLocalError

This code stops with UnboundLocalError. Rewrite add_points() without global, so that adding 50 and then 20 prints Points: 70.

points = 0

def add_points(amount):
    points = points + amount

add_points(50)
add_points(20)
print("Points:", points)

Exercise 3: A running total with nonlocal

Write make_till(), which returns a function add(price). Each call adds the price to a running total and returns the new total. Adding 450, 60 and 40 should print 450, 510 and 550.

Solutions

Solution 1

price = 100

def apply_offer():
    price = 80
    print("Inside:", price)

apply_offer()
print("Outside:", price)
Inside: 80
Outside: 100

price = 80 creates a local variable, so the global price is not changed.

Solution 2

points = 0

def add_points(current, amount):
    return current + amount

points = add_points(points, 50)
points = add_points(points, 20)
print("Points:", points)
Points: 70

The function takes the current points as a parameter and returns the new value, and the caller stores it.

Solution 3

def make_till():
    total = 0

    def add(price):
        nonlocal total
        total = total + price
        return total

    return add

till = make_till()
print(till(450))
print(till(60))
print(till(40))
450
510
550

nonlocal total lets add() change the total of make_till(), which the closure remembers between calls.

Common mistakes

  • Changing a global without global. stock = stock - 1 (or stock -= 1) inside a function gives UnboundLocalError: cannot access local variable 'stock' where it is not associated with a value. Pass the value in and return the result.
  • Hiding a built-in. After len = 5, calling len("Notebook") gives TypeError: 'int' object is not callable. Choose another name, like length.
  • Using nonlocal outside a nested function. In a normal top-level function, nonlocal count gives SyntaxError: no binding for nonlocal 'count' found. nonlocal only works for a variable of an enclosing function; for a top-level variable you would need global.
  • Using global everywhere. It hides where values change, as the bill example showed. Use parameters and return.

Frequently asked questions

What is the LEGB rule in Python?

LEGB is the order in which Python looks up a name: Local (the current function), Enclosing (functions around it), Global (the top level of the file) and Built-in (names like print and len). Python uses the first match it finds. If no scope has the name, you get NameError.

How do I fix UnboundLocalError in Python?

It happens when a function reads a name before assigning to it, because the assignment makes the name local in the whole function. The cleanest fix is to pass the value as a parameter and return the new value. If you must change a global, put global name at the top of the function; for an enclosing function’s variable, use nonlocal name.

What is the difference between global and nonlocal in Python?

global name makes the name refer to the variable at the top level of the file. nonlocal name makes it refer to the variable in the nearest enclosing function, so it only works inside a nested function. Both are needed only when you assign to the name; reading it works without them.

Summary

  • Variables assigned inside a function are local and disappear when it returns; top-level variables are global.
  • Python finds names in the order Local, Enclosing, Global, Built-in (LEGB); if blocks and for loops make no new scope.
  • Assigning to a name anywhere in a function makes it local everywhere in that function, which causes UnboundLocalError.
  • global changes a top-level variable, and nonlocal changes a variable of the enclosing function, as in a closure.
  • Prefer parameters and return to global variables; keep globals for constants in capital letters.

Next lesson

Next: Lesson 25, Python Lambda Functions: sorted() with key, map() and filter().

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *