The fleet galley has a tall stack of lunch trays. Rocket grabs one from the bottom, and the whole pile wobbles.
"Whoa! Steady!" he laughs. He slides it back.
Raven takes a tray from the top instead. "What do you notice about how a stack works?"
"You add to the top, and you take from the top," Rocket says.
Nova projects a tray with a function name on it. "Here is a hint. Python keeps its calls in a stack just like this."
Python keeps track of running functions in a call stack. Picture each call as a tray with the function name on it.
When a function is called, a new tray goes on top. When it returns, its tray comes off the top.
The function on the top tray is the one running right now. Every tray below it is waiting.
| Moment in the launch program | Trays, bottom to top |
|---|---|
| launch_probe() is called | launch_probe |
| launch_probe calls check_scanner | launch_probe, check_scanner |
| check_scanner calls check_lens | launch_probe, check_scanner, check_lens |
| check_lens returns | launch_probe, check_scanner |
| check_scanner returns | launch_probe |
| launch_probe returns | (empty) |
The stack grows as calls go deeper. It shrinks as each function returns. The last tray on is the first tray off.
def d():
print("d")
def c():
d()
def b():
c()
def a():
b()
a() def c():
print("c runs")
def b():
print("b starts")
c()
print("b ends")
def a():
b()
c()
a() | Statement | True or false? |
|---|---|
| A new call puts a tray on top. | ? |
| A return takes a tray from the bottom. | ? |
| The function on top is the one running. | ? |
| The same function can be on the stack at two different times. | ? |
Nice work! The call stack is how Python remembers where to go back to. Tomorrow we follow the values that come back.