Stop 08 · Intermediate PythonTopics · 3/10

Closures

Part of the Python Roadmap

In short

Functions in Python can create other functions, and those inner functions can remember values from where they were born. That memory is called a closure, and it's the secret behind decorators.

A closure is an inner function that remembers variables from the function that created it, even after that outer function has finished. Closures are the building block for decorators and function factories.

The jaadu walks out of a front door wearing a small backpack with a tiffin box and water bottle peeking out, waving goodbye.

Think of it like this

A school bag packed by Mom

Before you leave home, Mom packs your bag with a tiffin and a water bottle. Even after you've left home, those things are still with you. An inner function is the child, and the variables from the outer function are what got packed. The outer function finishing doesn't empty the bag.

Watch it happen

make_gst_calculator(0.18)

Outer runs
Inner made
rate packed
Inner called

1/4The outer function runs with rate = 0.18.

The big ideas

What you need to know

Functions are values

You can return a function from a function and store it in a variable like any other value.

Remembered variables

An inner function keeps access to the outer function's variables after the outer one returns.

Function factories

One outer function can create many customised functions, like a GST calculator for each rate.

nonlocal to change

To reassign a remembered variable inside the inner function, declare it nonlocal first.

See it in code

Walk through the code

python
1def make_gst_calculator(rate: float):2    def add_gst(amount: float) -> float:3        return round(amount * (1 + rate), 2)4    return add_gst5 6gst5 = make_gst_calculator(0.05)7gst18 = make_gst_calculator(0.18)8print(gst5(1000))     # 1050.09print(gst18(1000))    # 1180.010 11def make_counter():12    count = 013    def increment() -> int:14        nonlocal count15        count += 116        return count17    return increment18 19visitors = make_counter()20visitors()21visitors()22print(visitors())     # 323print(visitors.__closure__[0].cell_contents)   # 3

1/5The inner add_gst uses rate from the outer function, then the outer returns it.

A GST calculator factory and a counter that remembers its count between calls.

Save yourself the pain

Common mistakes

Oops

Writing count += 1 in the inner function without nonlocal and getting UnboundLocalError.

Do this instead

Add nonlocal count so Python knows you mean the outer variable.

Oops

Creating functions in a loop with lambda: i and finding they all use the last i.

Do this instead

Closures remember the variable, not its value at that moment. Bind it with a default: lambda i=i: i.

Your mission

Discount factory

~15 min

Quick check

Why is nonlocal needed in make_counter's inner function?

Go deeper

  1. 1Write make_multiplier(n) that returns a function multiplying by n.
  2. 2Use nonlocal to build a simple counter closure.
  3. 3Inspect a closure's __closure__ attribute to see the captured values.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge