Sub topic 4
Stepping through code: next, step, continue, return, until
This chapter covers the commands that move execution forward once you are stopped at a (Pdb) prompt. It assumes you can start a pdb session with breakpoint() or python -m pdb, and that you can read a traceback and follow Python functions, loops, and exceptions.
The model: pdb runs one line at a time
When pdb stops, it stops before a line runs. The line shown with -> is the line that will run next, not the one that just ran. Every stepping command tells pdb how far to run before it stops again. The commands differ in how they treat function calls, loops, and returns.
| Command | Short form | Runs until |
|---|---|---|
| `next` | `n` | the next line in the current function. Calls on that line run in full. |
| `step` | `s` | the next line that runs anywhere, including inside a called function |
| `return` | `r` | the current function is about to return |
| `until` | `unt` | a line number greater than the current one is reached, or the frame returns |
| `continue` | `c` | the next breakpoint, or the end of the program |
Pressing Enter on an empty line repeats the last command. This is useful for repeated n or s, but it can repeat something you did not intend, such as c.
A program to step through
Save this as stepdemo.py. It has a helper function, a loop, and a bug: the discount is applied to the wrong value.
def apply_discount(price, rate):
discount = price * rate
return price - discount
def total_cost(prices, rate):
total = 0
for price in prices:
adjusted = apply_discount(price, rate)
total += adjusted
return total
def main():
prices = [100, 50, 25]
breakpoint()
result = total_cost(prices, 10)
print("Total:", result)
main()The rate 10 is meant to be 0.10. Running the script shows a strange negative total, so you step through to find out where it goes wrong.
next: stay in the current function
> stepdemo.py(16)main()
-> result = total_cost(prices, 10)
(Pdb) n
> stepdemo.py(17)main()
-> print("Total:", result)
(Pdb) p result
-900next ran the whole call to total_cost, including everything inside it, and stopped on the following line of main. The result of -900 is wrong, but next hid how it was computed. Use next when you trust the code being called, or when you only care about the result.
step: go inside a call
Restart the program and use step at the same line.
> stepdemo.py(16)main()
-> result = total_cost(prices, 10)
(Pdb) s
--Call--
> stepdemo.py(6)total_cost()
-> def total_cost(prices, rate):
(Pdb) n
> stepdemo.py(7)total_cost()
-> total = 0
(Pdb) n
> stepdemo.py(8)total_cost()
-> for price in prices:
(Pdb) n
> stepdemo.py(9)total_cost()
-> adjusted = apply_discount(price, rate)
(Pdb) s
--Call--
> stepdemo.py(1)apply_discount()
-> def apply_discount(price, rate):
(Pdb) n
> stepdemo.py(2)apply_discount()
-> discount = price * rate
(Pdb) n
> stepdemo.py(3)apply_discount()
-> return price - discount
(Pdb) p discount
1000The --Call-- line tells you pdb entered a new function. Here discount is 1000 for a price of 100, so the rate is being treated as a multiplier of 10, not 10 percent. That points to the argument passed from main.
step has one limit. It can only enter functions written in Python. Calls into built-ins and C extensions, such as len() or sum(), run as a single step. Calls into library code written in Python do get entered, which can take you into long, unfamiliar files. If that happens, use r to get back out.
next versus step in practice
Use this diagram as a mental picture instead.
return: finish the current function
If you stepped into a function and do not need the rest of it, return runs until just before the function returns, then shows the return value.
(Pdb) r
--Return--
> stepdemo.py(3)apply_discount()->-900
-> return price - discountThe ->-900 at the end of the header line is the value about to be returned. After r you are still inside the function, on its return line. One more n takes you back to the caller, at the line that made the call.
return is the quickest way to answer the question "what did this function give back?" without walking through it line by line.
until: get past a loop
In a loop, next goes back to the top of the loop body on every iteration. If the loop runs 1,000 times, that is a lot of typing. until helps: without an argument, it continues until execution reaches a line with a number greater than the current line, so a backward jump to the top of the loop does not stop it.
In total_cost, suppose you are on line 10, total += adjusted, and want to leave the loop.
> stepdemo.py(10)total_cost()
-> total += adjusted
(Pdb) unt
> stepdemo.py(11)total_cost()
-> return totalThe exact stopping point depends on the code. The important behavior is that until does not stop at the jump back to line 8 or 9. In older Python versions and in some loop shapes, you may need to run until more than once, because the last line of the loop body can still jump backward.
You can also pass a line number: until 11 runs until a line number of 11 or more is reached in the current frame, or until the frame returns. This works as a one-off temporary stop. It does not create a breakpoint.
continue: run to the next stop
continue resumes the program. It stops again only at a breakpoint, at another breakpoint() call, at a crash, or when the program ends. If none of these happens, the program finishes and pdb exits.
A common pattern with breakpoint() inside a loop is that each c stops again on the next iteration, because the breakpoint() line runs again each time. To skip the remaining iterations, remove the call, set PYTHONBREAKPOINT=0, or use a conditional breakpoint, which later chapters cover.
If the program raises an exception while you are stepping, pdb shows the traceback and stays at the prompt. If you press c when no breakpoints remain and the program runs normally, the session ends and the script finishes.
Choosing the right command
- Start with
nto move through code you are checking line by line. - Use
sonly when the line contains a call you suspect. - Use
rwhen you entered a function by mistake or have seen enough of it. - Use
untto skip the remaining iterations of a loop. - Use
cwhen you are done, or when you want to reach the next breakpoint.
A good habit is to guess before each step what the next line will show. When the result differs from your guess, you have found something to investigate.
Common mistakes
- Stepping with
sinto library code. Standard-library and third-party frames are deep and slow to read. Userto leave, ornnext time. - Forgetting that the displayed line has not run yet. A variable assigned on the
->line does not have its new value until you run that line. - Pressing Enter by accident. An empty line repeats the previous command. After
corr, that can skip further than you meant. - Expecting
untilto skip every loop. It follows line numbers, so loops that jump backward in more than one place may need severaluntcommands. - Using a variable name that matches a pdb command. If your variable is called
n,c, ors, typing it runs the command instead. Usep nto print it, or!nto run the line as Python.
Putting it together
For the demo program, a short session finds the bug fast:
- Stop at the
breakpoint()and usesto entertotal_cost. - Use
nuntil the call toapply_discount, thensto enter it. - Use
rto see the returned value-900, and check the arguments withp price, rate. - Notice that
rateis10. Look back at the caller and fix the argument to0.10.
Exercise
You are stopped at a line that calls a function you wrote, and you want to see the first line inside that function. Which command do you use? Which command would you use to run the call without going inside, and which would you use after entering to get back out to the caller?
Show answer
Use step (s) to enter the function. Use next (n) to run the whole call and stop at the next line of the current function. After entering, use return (r) to run to the function's return and show its return value, then n once more to reach the caller.
Exercise
A for loop runs 500 times and you are stopped on the last line of its body. Using n would take you back to the top of the loop on each pass. Which command moves past the loop without stepping through each pass, and why does it work?
Show answer
Use until (unt). Without an argument it keeps running until execution reaches a line with a higher number than the current one, so the backward jump to the top of the loop does not stop it. The program runs the remaining iterations and stops on the first line after the loop.