LESSON 1.03 · 6 STAGES · 3 CONTROLS · 3 CHECKS
Function calls, scope and recursion
Watch calls push frames, name lookups search the scopes, and one default list stay shared.
EXPLAINER · 1.03 · CALL BAY
01
Stage 1 of 6 · Define a function
def makes a function object and binds the name outer to it. The body does not run yet.
Explain it simply
When Python runs a def line, it doesn't run the body. It builds a function object, a box that keeps the code for later. The name outer points to that box, like any other name. The body, lines 3 to 5 in the dashed outline, waits for a call.
The module frame binds x to the int 1 and outer to a function object with id 2368. Lines 3 to 5, the body of outer, have not run.
frame, nameobject and valuereferencefound, returned, new itemmiss, shared default
Toy: 3 short programs · up to 5 frames · CPython 3.12 rules · ids are short stand-ins for addresses
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
y
Which name in max(x, y, z) to follow.
fact(3)
How deep the recursion goes.
box=[]
One shared list, or a new list per call.
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
def binds the function name to a new function object.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
x = 1
def outer(y):
def inner(z):
print(y) # 2 (L no, E has it)
return max(x, y, z)
return inner(3)
print(outer(2)) # 3
def fact(n):
if n <= 1:
return 1 # the base case
return n * fact(n - 1)
r = fact(3)
print(r) # 6 (3 * 2 * 1)
def add(item, box=[]): # def makes this list once
box.append(item)
return box
a = add(1)
b = add(2)
print(a, b, a is b) # [1, 2] [1, 2] True
print(add.__defaults__) # ([1, 2],)
Copy it into a file and run it. Each print shows the result as a comment.
Common mix-ups
MYTHEach recursive call overwrites the same n.
FIXEach call gets its own frame and its own n. fact(3) keeps n = 3 while fact(2) runs.
MYTHA default list is made new for every call.
FIXdef makes the default once. Every call without box gets that same list.
Predict, then reveal
0 / 3 REVEALEDQ01Where does the lookup of max stop?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With fact(4), how many fact frames are on the stack at the base case?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03With box=None, what does a hold while add(2) runs?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Takeaways
- Each call, recursive or not, pushes a frame with its own local names.
- A name lookup tries local, enclosing, global, then built-in, and stops at the first match.
- def makes default values once, so a mutable default is shared.