Skip to content
dreamcode
dreamcode
Map
Closures
Lesson 51 of 77
+15 XP on finish
PYTHON ADVANCEDChapter 9 · Python Advanced

Closures

A function defined inside another function can use the outer function's variables, even after the outer function has finished. The inner function plus the variables it remembers is called a closure. Closures let you build customized functions on the fly. Use nonlocal when the inner function needs to change a remembered variable.

Worked example

How it reads

  • multiply remembers factor from the call that created it
  • Each call to make_multiplier makes a separate closure with its own factor
  • nonlocal count lets the inner function update the outer variable
Common mistakes
  • Assigning to an outer variable without nonlocal makes a new local variable, which raises UnboundLocalError when you read it first.
Cloud tip: Decorators are built from closures: the wrapper function remembers the function it wraps.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Make make_greeter return an inner function that takes a name and returns "{greeting}, {name}!". Then print(hello("Nova")) should show Hello, Nova!.

Press Run to check your work.