Using a debugger¶
The main features of a debugger are:
-
Breakpoints: pause the program when a particular line of code is about to be executed;
-
Display/print: show the current value of local variables;
-
Next: execute the current line of code and pause at the next line;
-
Continue: continue executing code until the next breakpoint, or the code finishes.
Slightly more advanced features include:
-
Conditional breakpoints: pause the program when a particular line of code is about to be executed and a specific condition is satisfied.
-
Step: execute the current line of code and pause at the first possible point — either the line in the current function or the first line in a function that is called.
-
Manual breakpoints: call
breakpoint()
in Python, andbrowser()
in R, to pause the program at the current line.
For example, consider the following code example:
first_demo.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
first_demo.R | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
-
We can use a conditional breakpoint to pause on line 4 (highlighted) only when
x = 42
. -
We can then use step to begin executing line 4 and pause on line 11, where we will see that
a = 42
. -
If we instead used next at line 4 (highlighted), the debugger would execute line 4 and then pause on line 5.
Try this yourself¶
Download either demo script and try setting breakpoints and stepping through the code.