Log inStart free
LESSON 1.06 · 5 STAGES · 3 CONTROLS · 3 CHECKSPRO · PREVIEW

Decorators and closures

Watch a decorator point a name at a wrapper whose cells outlive a call.


Pro lesson. Stage 1 is free to watch. Pro opens all 5 stages, 3 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 1.06 · CLOSURE BAY2 FRAMES · 2 CELLS · COUNT 0
01
Stage 1 of 5 · Call decorator
@counted runs the decorator. Its frame keeps fn and count in cells.
Explain it simply

Python builds the function square, but with @, no name points to it yet. It goes straight into counted, a decorator: a function that takes a function and returns a new one. counted's frame keeps fn and count in cells, small boxes that inner functions can share. Whatever counted returns will take the name square.

The stack holds the module frame and a frame for counted. Its name fn points to cell 2304, which holds the function square. count points to cell 2384, which holds 0.

name, framefunction, cell, valueid, referencenew this stage, resulterror
programcall stackheapdef counted(fn): count = 0 def wrapper(x): nonlocal count count += 1 return fn(x) return wrapper@counteddef square(x): """Square x.""" return x * xsquare(3)<module>countedcounted(square)fncellcountcellfunction counted · id 2208__closure__Nonefunction square · id 2272__closure__None__doc__'Square x.'cell2304cell23840programcall stackheapdef counted(fn): count = 0 def wrapper(x): nonlocal count count += 1 return fn(x) return wrapper@counteddef square(x): """Square x.""" return x * xsquare(3)<module>countedcounted(square)fncellcountcellfunction counted · id 2208__closure__Nonefunction square · id 2272__closure__None__doc__'Square x.'cell2304cell23840
Toy: 1 decorator · 1 call · at most 3 frames · ints drawn inline · ids are short stand-ins
STAGE 1 / 5
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
fn→cell→function square\sy{fn}{ink}{\texttt{fn}} \to \sy{cell}{data}{\mathrm{cell}} \to \sy{f}{data}{\mathrm{function}\ \texttt{square}}
fn→cell 2304→id 2272;count→cell 2384→0\texttt{fn} \to \mathrm{cell}\ 2304 \to \mathrm{id}\ 2272;\quad \texttt{count} \to \mathrm{cell}\ 2384 \to 0

fn points to a cell, and the cell holds the function.

Common mix-ups

MYTHThe decorator changes the function square itself.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01Without nonlocal, what does count += 1 do on the first call?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 5
Unlock the full explainer
  • 4 more stages and 3 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.