Python Debugging and Testing with pdb

Debugging and testing are essential aspects of software development. In Python, the Python Debugger, commonly known as pdb, is a powerful tool that can help you identify and fix issues in your code efficiently. This comprehensive guide will walk you through the intricacies of using pdb effectively, providing real-world examples and step-by-step instructions to enhance your debugging and testing skills in Python.

What is Python Debugger (pdb)?

Python Debugger, or pdb, is a built-in module that allows you to interactively debug your Python code. It provides a set of commands and features that enable you to:

  1. Set breakpoints to pause execution at specific points in your code.
  2. Examine variables and their values at any point during execution.
  3. Step through your code line by line.
  4. Evaluate expressions to understand their behavior.
  5. Control program flow during debugging.
  6. Trace the call stack to identify the source of errors.

Getting Started with pdb

Let’s start by exploring some basic pdb commands and how they can be used in a real Python program.

Example 1: Debugging a Simple Python Script

Consider the following Python script example.py:

def divide(x, y):
    result = x / y
    return result
num1 = 10
num2 = 0
result = divide(num1, num2)
print(f"Result: {result}")

In this script, we’re attempting to divide num1 by num2, which could result in a ZeroDivisionError. To debug this code using pdb, follow these steps:

Import pdb and set a breakpoint:

import pdb
pdb.set_trace()

Run the script.

The program will pause at the breakpoint, and you’ll enter the pdb interactive mode. You can now use various commands to inspect and control the program’s execution.

pdb Commands

  • n (next): Execute the current line and move to the next line.
  • c (continue): Resume program execution until the next breakpoint.
  • q (quit): Exit the debugger and terminate the program.
  • p (print): Print the value of a variable or expression.
  • l (list): Display the code surrounding the current line.
  • s (step into): Step into a function call.
  • r (return): Continue until the current function returns.

Example 2: Debugging a Function

Let’s say we have a function calculate_average in a file math.py:

def calculate_average(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return average

To debug this function using pdb, create a script:

import pdb
from math import calculate_average
data = [10, 20, 30, 40]
result = calculate_average(data)
print(f"Average: {result}")

Set a breakpoint using pdb.set_trace() and follow the same debugging steps as in Example 1.

Author: user