Debugging in Python - A Cakewalk With PDB - by Rachit Tayal - Python Features - Medium

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

22/07/2020 Debugging in Python — A cakewalk with pdb | by Rachit Tayal | Python Features | Medium

You have 2 free stories left this month. Sign up and get an extra one for free.

Photo by Kevin Ku on Unsplash

Debugging in Python — A cakewalk with pdb


Interactive Debugging using Python standard pdb module explained!!

Rachit Tayal
Sep 9, 2019 · 5 min read

We all encounter bugs in our code while developing programs. Using the print function
can help us track down the source of many issues. Writing tests for specific cases that
https://medium.com/python-features/debugging-in-python-a-cakewalk-with-pdb-cd748ca62ee7 1/6
22/07/2020 Debugging in Python — A cakewalk with pdb | by Rachit Tayal | Python Features | Medium

cause trouble is another great way to isolate problems.

But these tools aren’t enough to find every root cause. When we need something more
powerful, it’s time to try Python’s built-in interactive debugger. The debugger lets us
inspect program state, print local variables, and step through a Python program one
statement at a time.

In most other programming languages, we use a debugger by specifying what line of a


source file we’d like to stop on, then execute the program.

In contrast, with Python the easiest way to use the debugger is by modifying our
program to directly initiate the debugger just before we think we’ll have an issue worth
investigating. There is no difference between running a Python program under a
debugger and running it normally.

To initiate the debugger, all we have to do is import the pdb built-in module and run its
set_trace function. We’ll often see this done in a single line so programmers can
comment it out with a single # character when required.

def complex_func(x, y, z):


# ...
import pdb; pdb.set_trace()

When above statement gets executed, the program will pause its execution. The
terminal that started our program will turn into an interactive Python shell.

-> import pdb; pdb.set_trace()


(Pdb)

At the (Pdb) prompt, we can type in the name of local variables to see their values
printed out. We can see a list of all local variables by calling the locals built-in function.
We can import modules, inspect global state, construct new objects, run the help built-
in function, and even modify parts of the program-whatever we need to do to aid our
debugging.

To demonstrate the usage, let’s create a sample code.

https://medium.com/python-features/debugging-in-python-a-cakewalk-with-pdb-cd748ca62ee7 2/6
22/07/2020 Debugging in Python — A cakewalk with pdb | by Rachit Tayal | Python Features | Medium

# demo.py
import pdb

def add(a, b):


return a + b

def func():
pdb.set_trace() # -- added breakpoint
age = 26
print("Hello Sarah!!")
print("Hello World!!")
result = add("buggy", age)
print('Just an extra print')
return result

func()

If we look at it, calling the func() will throw an error since it tries to add a string with
age(26) and we can’t add an int and a string , but let’s pretend we don’t know the

error yet and start debugging.

Upon running the code, pdb’s debugger console starts where set_trace() is placed,
waiting for our instructions.

$ python3 demo.py
-> age = 26
(Pdb)

The arrow mark points to the line that will be run next by pdb.
So Let’s see how do we navigate from here!

Execute the next line with — n (next):


Upon entering n , the line age = 26 will get executed.

(Pdb) n
-> print("Hello Sarah!!")
(Pdb)

Now the bottom most arrow mark tells us what line will be executed next.

Repeat previous command with — Enter key:

https://medium.com/python-features/debugging-in-python-a-cakewalk-with-pdb-cd748ca62ee7 3/6
22/07/2020 Debugging in Python — A cakewalk with pdb | by Rachit Tayal | Python Features | Medium

Now to execute the next line we can either hit n again. Or just typing the enter key will
repeat the previous command issued.

(Pdb)
Hello Sarah!!
-> print("Hello World!!")

Print the variable values with — p (print):


We can print local variables, program state using the p command followed by variable
name.

(Pdb) p age
26
(Pdb)

See source code around current line with — l (list):


We can use the l (list) command to look around few lines above and below the next
statement to be executed.

(Pdb) l
6
7 def func():
8 pdb.set_trace() # -- added breakpoint
9 age = 26
10 print("Hello Sarah!!")
11 print("Hello World!!")
12 -> result = add("buggy", age)
13 print('Just an extra print')
14 return result
15
16 func()
(Pdb)

Step into a subroutine with — s (step):


The next line waiting to run is a function add("buggy", age) .

If we suspect something could be wrong here, we can step into this function using s

command and start running this function line-by-line.

https://medium.com/python-features/debugging-in-python-a-cakewalk-with-pdb-cd748ca62ee7 4/6
22/07/2020 Debugging in Python — A cakewalk with pdb | by Rachit Tayal | Python Features | Medium

-> result = add("buggy", age)


(Pdb) s
--Call--
-> def add(a, b):
(Pdb)

Continue till current function returns with — r (return):


Although our add() routine is short, but if we entered into a rather lengthy method, we
can continue until the method returns by issuing the r command.

(Pdb) r
--Return--
-> return a + b
(Pdb)

Stop debugger and continue running normally using — c (continue):


If we are done with the debugging and want the program to continue normally, we can
use the c command.

(Pdb) c
Traceback (most recent call last):
File "demo.py", line 16, in <module>
func()
File "demo.py", line 12, in func
result = add("buggy", age)
File "demo.py", line 4, in add
def add(a, b):
TypeError: can only concatenate str (not "int") to str

In our case, we will also be able to get the root cause of the error present in our code.
Et. Voila!! 🍻
Quit debugging abruptly with — q (quit):
If we want to quit the debugger abruptly, we can issue the q command.

So to summarize some of the debugger commands what we learned:

Command Key Description


Next n Execute the next line
Print p print value of variable following p
https://medium.com/python-features/debugging-in-python-a-cakewalk-with-pdb-cd748ca62ee7 5/6
22/07/2020 Debugging in Python — A cakewalk with pdb | by Rachit Tayal | Python Features | Medium

Repeat Enter Repeat the last entered command


List l Show few lines above and below the current line
Step s Step into a subroutine
Return r Run until current sub routine returns
Continue c Stop debugging breakpoint and continue normally
Quit q Quit pdb abruptly

Therefore we covered a few basic and common uses of pdb. This should be good
enough to get us up and running fairly quickly and painlessly. Also, for those curious
about learning more can refer Python’s pdb docs.

The best way to gain better understanding is to fire up the interactive session and get
your hands dirty. Happy Debugging!

Conclusions:
We can initiate Python interactive debugger at a point of interest directly in our
program with set_trace() method.

The Python debugger prompt is a full Python shell that lets us inspect and modify
the state of a running program.

pdb shell commands let us precisely control programs execution, allowing us to


alternate between inspecting program state and progressing program execution.

Programming Python Debugging

About Help Legal

Get the Medium app

A button that says 'Download on the A button that says 'Get it on,
App Store', and if clicked it will lead Google Play', and if clicked it will lead
you to the iOS App store you to the Google Play store

https://medium.com/python-features/debugging-in-python-a-cakewalk-with-pdb-cd748ca62ee7 6/6

You might also like