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
def outer():
message = "Hello"
def inner():
print(message)
return inner
func = outer()
func()
Output
Hello
Even though outer() finished, inner() still remembers message.
How It Works
outer()createsmessageinner()usesmessageouter()returnsinner- The returned function remembers the value
Custom Multiplier Example
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
10
15
Each function remembers its own value of n.
Private Counter Example
def counter():
count = 0
def inner():
nonlocal count
count += 1
print(count)
return inner
run = counter()
run()
run()
run()
Output
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:
Hello name
Mini Challenge
Create a function:
make_power(n)
It returns a function that raises a number to power n.
Example:
square = make_power(2)
cube = make_power(3)
print(square(4))
print(cube(2))
Expected output:
16
8
Real World Use Case
Closures are used in decorators, callbacks, factories, configuration tools, and stateful functions.
Quiz
- What is a closure?
- What does a closure remember?
- Why is
nonlocaluseful? - 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.