Fundamentals 4 min read

Using pdb and ipdb: Basic Usage and 10 Practical Debugging Scenarios in Python

This article introduces Python's interactive debuggers pdb and ipdb, explains their core commands, and provides ten practical code examples covering breakpoints, stepping, variable inspection, conditional breakpoints, exception handling, and remote debugging to help developers efficiently troubleshoot and improve code quality.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using pdb and ipdb: Basic Usage and 10 Practical Debugging Scenarios in Python

In Python, several interactive debuggers such as pdb and ipdb help developers step through code, inspect variables, set breakpoints, and more.

1. Using pdb debugger:

import pdb

def divide(x, y):
    result = x / y
    return result
pdb.set_trace()  # set breakpoint
divide(10, 0)

2. Common pdb commands:

- n: execute next line
- s: step into function
- c: continue until next breakpoint
- l: list source code context
- p <variable>: print variable value
- q: quit debugger

3. Using ipdb debugger:

import ipdb

def divide(x, y):
    result = x / y
    return result

ipdb.set_trace()
divide(10, 0)

4. ipdb commands are similar to pdb .

5. Tracing code execution flow:

import pdb

def foo():
    print("foo")
    bar()

def bar():
    print("bar")

pdb.set_trace()
foo()

6. Viewing variable values:

import pdb

def foo():
    x = 10
    pdb.set_trace()
    y = x + 5
    print(y)

foo()

7. Jumping to a specific line:

import pdb

def foo():
    print("foo")
    pdb.set_trace()
    print("bar")

foo()

8. Setting conditional breakpoints:

import pdb

def foo():
    for i in range(10):
        pdb.set_trace()  # set breakpoint
        print(i)

foo()

9. Entering debugger on exception:

import pdb

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        pdb.post_mortem()  # enter debugger on exception
    return result

divide(10, 0)

10. Remote debugging:

import pdb
import remote_pdb

def foo():
    print("foo")
    remote_pdb.set_trace(host='0.0.0.0', port=4444)  # start remote debugger
    print("bar")

foo()

These examples demonstrate common uses of pdb and ipdb , which can be adapted and extended to suit various debugging needs, improving development efficiency and code quality.

debuggingCode Exampleipdbpdb
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.