CodingNic

Intermediate Python

Closures

Intermediate Python 32 min read

Closures

Closures

Functions in Python can do more than run code.

They can create other functions and remember values from earlier.

This idea is called a closure.

What Is a Closure?

A closure is an inner function that remembers variables from the outer function even after the outer function has finished.

Why Closures Matter

Closures help you:

  • keep data private
  • create custom functions
  • remember values
  • build decorators

First Example

python
def outer():
    message = "Hello"

    def inner():
        print(message)

    return inner

func = outer()
func()

Output

text
Hello

Even though outer() finished, inner() still remembers message.

How It Works

  1. outer() creates message
  2. inner() uses message
  3. outer() returns inner
  4. The returned function remembers the value

Custom Multiplier Example

python
def multiply_by(n):
    def inner(x):
        return x * n
    return inner

double = multiply_by(2)
triple = multiply_by(3)

print(double(5))
print(triple(5))

Output

text
10
15

Each function remembers its own value of n.

Private Counter Example

python
def counter():
    count = 0

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

    return inner

run = counter()

run()
run()
run()

Output

text
1
2
3

What Is nonlocal?

nonlocal lets the inner function change a variable from the outer function.

Without it, Python treats count as a new local variable.

Why Closures Are Powerful

They let functions carry their own saved data.

Code Along

Create a function make_greeting(name).

Return an inner function that prints:

text
Hello name

Mini Challenge

Create a function:

python
make_power(n)

It returns a function that raises a number to power n.

Example:

python
square = make_power(2)
cube = make_power(3)

print(square(4))
print(cube(2))

Expected output:

text
16
8

Real World Use Case

Closures are used in decorators, callbacks, factories, configuration tools, and stateful functions.

Quiz

  1. What is a closure?
  2. What does a closure remember?
  3. Why is nonlocal useful?
  4. Where are closures commonly used?

Assignment

Create a closure that remembers a city name and prints a welcome message.

Summary

You learned how closures let inner functions remember values from outer functions.