Reading history

Python Scope, global, nonlocal and Closures

5 min read 1 views

Understand Python scope with the LEGB rule, the global and nonlocal keywords, UnboundLocalError, closures and the late-binding trap with lambdas in loops.

Every name in Python lives in a scope, the part of the program where that name can be seen. Knowing which scope a name belongs to explains puzzling errors such as UnboundLocalError, and it leads to one of Python’s most useful tools: the closure, a function that remembers variables from the place where it was created. This lesson covers the LEGB rule, the global and nonlocal keywords, and closures.

In this lesson you will learn

  • The LEGB rule: Local, Enclosing, Global, Built-in
  • When you need the global keyword
  • Why UnboundLocalError happens
  • Closures and the nonlocal keyword
  • The late-binding trap with lambdas in loops

You should know functions and lambda functions.

The LEGB Rule and the global Keyword

When Python meets a name, it looks for it in four places, in this order: the Local function, any Enclosing functions, the module’s Global names, and finally the Built-in names such as len and print. It uses the first match it finds.

# LEGB: Local, Enclosing, Global, Built-in
city = "Dhaka"                      # global

def outer():
    city = "Chattogram"             # enclosing (for inner)
    def inner():
        city = "Sylhet"             # local
        print("inner sees:", city)
    inner()
    print("outer sees:", city)

outer()
print("module sees:", city)
print("built-in len still works:", len(city))

# Reading a global is fine; assigning needs the global keyword
visitors = 0

def visit():
    global visitors
    visitors += 1

visit(); visit(); visit()
print("visitors =", visitors)

# Without global, assignment makes the name local for the WHOLE function
def broken():
    try:
        visitors += 1               # noqa: F823
    except UnboundLocalError as e:
        print("UnboundLocalError:", e)

broken()

Output

inner sees: Sylhet
outer sees: Chattogram
module sees: Dhaka
built-in len still works: 5
visitors = 3
UnboundLocalError: cannot access local variable 'visitors' where it is not associated with a value
  • There are three different variables called city. Each function sees the nearest one, so inner prints Sylhet, outer prints Chattogram and the module prints Dhaka. Assigning inside a function never changes the outer variables.
  • len is not defined anywhere in the file, so Python finds it in the built-in scope.
  • A function may read a global variable freely, but to assign to it, it must say global visitors first. Then visitors += 1 changes the module’s variable.
  • In broken() there is an assignment to visitors and no global, so Python decides, before the function runs, that visitors is local for the whole function. The += then tries to read a local that has no value yet, which raises UnboundLocalError.

Closures and nonlocal

# A closure remembers variables from the function that created it
def make_counter(start=0):
    count = start
    def step():
        nonlocal count               # change the enclosing variable
        count += 1
        return count
    return step

tickets = make_counter()
orders = make_counter(100)
print(tickets(), tickets(), tickets())
print(orders(), orders())
print("tickets still at", tickets())

# Closures as small configurable functions
def make_vat(rate):
    def add_vat(price):
        return round(price * (1 + rate), 2)
    return add_vat

vat15 = make_vat(0.15)
vat5 = make_vat(0.05)
print(vat15(200), vat5(200))
print("remembered:", vat15.__closure__[0].cell_contents)

# The late-binding trap in loops
late = [lambda: i for i in range(3)]
fixed = [lambda i=i: i for i in range(3)]
print("late:", [f() for f in late])
print("fixed:", [f() for f in fixed])

Output

1 2 3
101 102
tickets still at 4
230.0 210.0
remembered: 0.15
late: [2, 2, 2]
fixed: [0, 1, 2]
  • make_counter returns the inner function step. Even after make_counter has finished, step still remembers its count. A function bundled with remembered variables like this is a closure.
  • Each call to make_counter creates a new, separate count, so tickets and orders count independently.
  • nonlocal count lets step assign to the enclosing function’s variable. Without it, count += 1 would raise UnboundLocalError, for the same reason as before.
  • make_vat(0.15) builds a small, ready-configured function. You can see the remembered value in __closure__, although you rarely need to.
  • The last example is a classic trap. Each lambda looks up i when it is called, not when it is created, and by then the loop has finished with i = 2. Writing lambda i=i: i copies the current value into a default argument, which is fixed at creation time.

global or nonlocal?

KeywordLets you assign toTypical use
(none)Only local names; outer names can be readMost functions
global xThe module-level xSimple scripts, settings, counters
nonlocal xThe nearest enclosing function’s xClosures that keep state

Common Mistakes

  1. Using global to pass data around. Functions that change globals are hard to test. Prefer parameters and return values.
  2. Naming a variable after a built-in, such as list = [1, 2]. The built-in list() is then hidden in that scope.
  3. Expecting a loop variable to be captured by value in a lambda or inner function. Use a default argument or functools.partial.
  4. Using nonlocal for a module-level name. It only works for variables of an enclosing function; use global for module names.

Practice Exercises

Exercise 1. Write make_multiplier(n) that returns a function multiplying its argument by n.

Show answer
def make_multiplier(n):
    def times(x):
        return x * n
    return times

double = make_multiplier(2)
print(double(21))   # 42

Exercise 2. Write a closure make_average() whose returned function takes a new number each call and returns the running average.

Show answer
def make_average():
    total = count = 0
    def add(x):
        nonlocal total, count
        total += x
        count += 1
        return total / count
    return add

avg = make_average()
print(avg(10), avg(20), avg(60))   # 10.0 15.0 30.0

Frequently Asked Questions

Do if blocks and for loops create a new scope?

No. In Python only functions, classes, modules and comprehensions create scopes. A variable set inside an if or for block is still available after the block ends.

How are closures related to decorators?

A decorator is usually a function that returns a closure. The inner wrapper function remembers the original function from the enclosing scope and calls it, adding behaviour before or after.

Summary

  • Python looks up names in Local, Enclosing, Global, then Built-in scope.
  • Assigning inside a function makes the name local unless you declare global or nonlocal.
  • A closure is an inner function that remembers variables from where it was made.
  • Lambdas in loops see the variable’s final value; bind it with a default argument.

Next: Python functools Module.

Lessons are also marked complete when you click Next.

Leave a Reply

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