Intermediate Python · Lesson 2 of 14

Scope and closures

Learn how Python finds a name (local, enclosing, global, built-in), when to use global and nonlocal, and how closures let functions remember values.

About 16 minutes · code runs in your browser, nothing to install

Scope is the part of a program where a name can be seen. When you use a name, Python looks for it in four places, in this order, and stops at the first match:

  • Local: names created inside the current function.
  • Enclosing: names in a function that contains the current one.
  • Global: names created at the top level of the file.
  • Built-in: names Python always has, like len and print.

People remember the order as LEGB.

Pythoneditable
city = "Global city"

def outer():
    city = "Enclosing city"
    def inner():
        print("inner sees:", city)
    inner()

outer()
print("top level sees:", city)
print("len is built in:", len("abc"))
Output
inner sees: Enclosing city
top level sees: Global city
len is built in: 3

inner() has no city of its own, so Python finds the one in outer().

Changing a global variable

Reading a global name inside a function is fine. Assigning to it creates a new local name instead, unless you declare it with global and nonlocal. Using a name before assigning it locally causes an UnboundLocalError.

Pythoneditable
visits = 0

def broken():
    try:
        visits = visits + 1
    except UnboundLocalError:
        print("Error: visits is local here and has no value yet")

def count_visit():
    global visits
    visits = visits + 1

broken()
count_visit()
count_visit()
print("Visits:", visits)
Output
Error: visits is local here and has no value yet
Visits: 2
Tip: Global variables make programs hard to follow, because any function can change them. Prefer passing values in as arguments and sending results back with return.

nonlocal: changing an enclosing variable

nonlocal does for an enclosing function what global does for the file: it lets an inner function assign to a name that belongs to the outer function.

Closures: functions that remember

When an outer function returns an inner function, the inner one keeps access to the outer function's variables, even after the outer function has finished. That combination is called a closure. It is a light way to build a function with some settings baked in.

Pythoneditable
def make_multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))

def make_counter():
    count = 0
    def next_number():
        nonlocal count
        count += 1
        return count
    return next_number

ticket = make_counter()
print(ticket(), ticket(), ticket())
Output
20 30
1 2 3

Each call to make_counter() creates its own count, so two counters would not share numbers.

The late binding trap

A closure remembers the variable, not its value at the moment the function was made. Functions created in a loop all see the loop variable's final value. Fix it by copying the value into a default argument.

Pythoneditable
funcs = []
for i in range(3):
    def show():
        return i
    funcs.append(show)
print([f() for f in funcs])

fixed = []
for i in range(3):
    def show(i=i):
        return i
    fixed.append(show)
print([f() for f in fixed])
Output
[2, 2, 2]
[0, 1, 2]

✎ Exercise

Write make_discount(percent) that returns a function. The returned function takes a price and gives back the price minus percent per cent, rounded to 2 places.

Hint: Define an inner function that uses percent, then return the inner function without calling it (no brackets).

Your codewrite your answer, then Run
def make_discount(percent):
    # your code here
    pass

sale = make_discount(20)
black_friday = make_discount(35)
print(sale(50))
print(black_friday(19.99))

Expected output:

40.0
12.99
Show a solution
Solutioneditable
def make_discount(percent):
    def apply(price):
        return round(price * (1 - percent / 100), 2)
    return apply

sale = make_discount(20)
black_friday = make_discount(35)
print(sale(50))
print(black_friday(19.99))
Output
40.0
12.99

Check yourself

1. In what order does Python look up a name?

2. Which keyword lets an inner function assign to a variable of its outer function?

3. What is a closure?

Spotted a mistake on this page? Tell us