Debugging in Python

A guide to knowing and implementing the Python debugger module.

Jayashree domala
3 min readOct 22, 2020

The Python module used to debug the code is called as “pdb”. It provides an interactive debugging program for Python programs. It has features that allow you to pause the program, check the values of different variables and watch the step-by-step execution of the program. This helps in finding bugs in the logic.

Let’s consider a code with an error to see how this works.

>>> import pdb>>> a = [11,44,77]
>>> b = 1
>>> c = 9
>>> result = b + c
>>> print(result)
# wrong line of code
>>> result2 = a + b
>>> print(result2)
10
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-29b30ba110f3> in <module>
7
8 # wrong line of code
----> 9 result2 = a + b
10 print(result2)
TypeError: can only concatenate list (not "int") to list

So as you can see there is an error because a list and integer cannot be added. Now we will set a trace using the module. So go to the line where there is an error and trace it. When this code is run, the interactive debugging environment is shown. Press ‘q’ to quit the debugging environment.

Source: Author
>>> a = [11,44,77]
>>> b = 1
>>> c = 9
>>> result = b + c
>>> print(result)
>>> pdb.set_trace()# wrong line of code
>>> result2 = a + b
>>> print(result2)
10
--Return--
None
> <ipython-input-3-c41ee9df98d8>(8)<module>()
6 print(result)
7
----> 8 pdb.set_trace()
9
10 # wrong line of code
ipdb> q
---------------------------------------------------------------------------
BdbQuit Traceback (most recent call last)
<ipython-input-3-c41ee9df98d8> in <module>
6 print(result)
7
----> 8 pdb.set_trace()
9
10 # wrong line of code
D:\Anaconda3\lib\bdb.py in trace_dispatch(self, frame, event, arg)
90 return self.dispatch_call(frame, arg)
91 if event == 'return':
---> 92 return self.dispatch_return(frame, arg)
93 if event == 'exception':
94 return self.dispatch_exception(frame, arg)
D:\Anaconda3\lib\bdb.py in dispatch_return(self, frame, arg)
152 finally:
153 self.frame_returning = None
--> 154 if self.quitting: raise BdbQuit
155 # The user issued a 'next' or 'until' command.
156 if self.stopframe is frame and self.stoplineno != -1:
BdbQuit:

Refer to the notebook here.

Beginner-level books to refer to learn Python:

Advance-level books to refer to learn Python:

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Jayashree domala

Self-driven woman who wishes to deliver creative and engaging ideas and solutions in the field of technology.