Debugging in Python 3.x or earlier using Built-in Methods – pdb

Python tutorial to learn to debug using built-in tool pdb. Please read this full tutorial to learn to debug.

Why DEBUGGING

A debugger is a scripted program used by programmers to test and debug a specific script or program. A Debugger uses instruction-set simulators, rather than executing the script directly onto the processor to achieve a better and enhanced control level over the execution. This is done to avoid future errors and complications and to ensure smooth functioning of the script.

Debugging in Python 3.x or earlier

There are various Python 3.x or earlier debugging tools such as pdb, pudb, pydb, and  pydbgr

In this Tutorial, we will discuss Python 3.x ‘s built-in debugger ‘pdb
.Pdb, is an interactive tool that helps in examining the code execution step by step.

Pdb – Built-in Debugger

It allows us to stop the execution of a program at a chosen instruction called a breakpoint, and evaluate the various expressions in the current context. The debugger also allows us to examine the continuity of the code, as well as the status of various objects in the current function being executed which collectively constitute the stack frame corresponding to that function.

In order to debug a program in Python shell. We need to import the module pdb as well as the script to be debugged.

import pdb 
import <file name> as m
pdb.run('m.main()')
Output: > <string>(1)<module>() -> None 
        (Pdb)

Python debugger uses the prompt (Pdb) to indicate that the program is executing in the debugging mode.



Another way to execute a program in debugging mode is by including the following two lines in the script:

import pdb 
pdb.set_trace()

Note that including the above two lines at the beginning of the program will increase every line number by two. If we invoke the function set_trace () at the very beginning. The program would run in debugging mode right from the first instruction to be executed. However, since we know that the bug exists in the script function, we may invoke set_trace() within the function body. 

Also learn,
An introduction to classes and objects in python
How to Define Functions in Python?

In this tutorial, we will learn about implementing Pdb debugger in Python 3.x or earlier on sample code.

 

Sample.py

def adder(a, b):
    return a + b

def samplefunc():
    var = 1
    print("Line 1 executed")
    print("Line 2 executed")
    out = adder("CodeSpeedy", var)
    print('Line 3 executed')
    return out

samplefunc()

The sample code defines two functions. The samplefunc() function calls add() from within.If you look at it, clearly, calling the samplefunc()  will throw an error upon hitting the add() because it tries to add a string CodeSpeedy” with the number 10. You can’t add an integer and a string.

But let’s pretend we don’t know where the error is and start debugging instead using the inbuilt debugger in Python 3.x.

As in part 1, we have already discussed settrace() function, let us implement here and debug our code.

Settrace() Implementation

import pdb
def adder(a, b):
    return a + b

def samplefunc():
    pdb.settrace()    # breakpoint added
    var = 1
    print("Line 1 executed")
    print("Line 2 executed")
    out = adder("CodeSpeedy", var)
    print('Line 3 executed')
    return out

samplefunc()  
$Python3 sample.py
-> var=1
(pdb)

Upon execution of the code, pdb’s debugger console starts where settrace() is placed, waiting for your instructions. The arrow points to the line that will be executed next by pdb.

Now for executing and debugging further lines, we make use of the next keyword.

Debugging the next line

(pdb)n
-> print('Line 1 executed')
(pdb)

Now to debug the next line you can either write ‘n’ again. Or just press the enter key will repeat the previous command executed.

Jumping to the next line using the enter key

(pdb)
Line 1 executed
-> print('Line 2 executed')
(pdb)

This process is continued until the function encounters the return statement.

          Stopping debugger by using the continue statement

pdb c
$

After all the lines are debugged we can stop the debugger using continue command .

Quitting debugging abruptly

(Pdb) q
Traceback (most recent call last):
  File "sample.py", line 16, in <module>
    samplefunc()
  File "sample.py", line 12, in samplefunc
    out = adder("CodeSpeedy", var)
  File "/Users/selva/anaconda3/lib/python3.6/bdb.py", line 110, in dispatch_exception
    if self.quitting: raise BdbQuit
bdb.BdbQuit
$

If we want to quit the debugger abruptly we use the quit command.

We will be getting deep in to debugging and understand the concept at an advanced level in my future blogs. Stay tuned to grasp the knowledge. Till then you can also learn,
First Class Citizens in Python 3.x or earlier
Formatting of Strings in Python

Leave a Reply

Your email address will not be published. Required fields are marked *