← Back to list

A Guide to Debugging with ipdb.set_trace()

Debugging can be a challenging but essential part of programming. One of the most powerful tools in the Python debugging toolkit is `ipdb`…

Linda Ta · 2024-09-13 12:51 · 1 claps · 5.5 min read
#ipdb #debugging-python #beginner
Open on Medium ↗
Wiki topics: 💻 · Programming

A Guide to Debugging with ipdb.set_trace()

Debugging can be a challenging but essential part of programming. One of the most powerful tools in the Python debugging toolkit is ipdb, an enhanced version of the built-in pdb module. This guide will walk you through how to use ipdb.set_trace() to debug Python code and see how it differs from the standard Python REPL (Read-Eval-Print Loop).

REPL and ipdb

REPL stands for Read, Evaluate, Print, Loop. It is an interactive programming environment that processes user input and provides immediate feedback. The Python shell is an example of a REPL; when you type python in your terminal, you enter this environment. Every command you enter is read, evaluated, and the result is printed back to you, creating a loop of interaction.

ipdb stands for “IPython Debugger,” and is a more advanced version of Python’s built-in debugger, pdb. While pdb provides basic debugging functionality, ipdb enhances this with features such as tab completion, syntax highlighting, and better tracebacks. Essentially, ipdbis a REPL that you can inject directly into your program.

Before you can use ipdb, you need to install it. Open your terminal and run:

> pipenv install
> pipenv shell

“NOTE: This will only install ipdb in your virtual environment. If you want to install ipdb system-wide, you must exit your virtual environment and run the following command in your local environment:”

> pip install ipdb

(https://github.com/learn-co-curriculum/python-p3-debugging-with-ipdb , 2024)

Using ipdb.set_trace()

The main feature of ipdb is the set_trace() function, which sets a breakpoint in your code. A breakpoint is a point where you want the program to pause so you can inspect what’s happening. Here’s a simple example:

# example.py

import ipdb

def divide(a, b):
    ipdb.set_trace()  # This is where the debugger will pause
    return a / b

result = divide(10, 2)
print(result)

When you run this script(“python example.py”), execution will halt at the ipdb.set_trace() line, and you can use the ipdb interactive prompt.

Basic Commands in ipdb

Once inside the ipdb prompt, you can use various commands to inspect and control the execution of your code. Here’s a handy cheatsheet of common ipdb commands:

  • **n (next)**: Execute the next line of code. If the next line is a function call, it will step into that function. This is useful for stepping through the code line by line.
  • **s (step)**: Step into the function call and pause at the first line of that function.
  • **c (continue)**: Continue execution until the next breakpoint is encountered. This command is useful when you want to bypass intermediate breakpoints.
  • **l (list)**: List the source code around the current line. By default, it lists 11 lines of code centered around the current line, which can be adjusted with additional arguments.
  • **b (breakpoint)**: Set a new breakpoint at a specified line number or function.
  • **p (print)**: Print the value of an expression.
  • **pp (Pretty-print)**: Pretty-print the value of an expression.
  • **tbreak**: Set a temporary breakpoint that is removed after being hit once.
  • **where**: Show the call stack at the current point of execution.
  • **args**: Display the arguments of the current function.
  • **q (quit)**: Exit the debugger and stop the program.
  • **h (help)**: Display a list of available commands or help for a specific command.

Example Debugging

Let’s go through a practical example to see how ipdb works in action.

# example.py

def add_numbers(a, b):
    import ipdb; ipdb.set_trace()  # <-- Set a breakpoint
    result = a + b
    return result

def main():
    num1 = 3
    num2 = 4
    sum_result = add_numbers(num1, num2)
    print(f"The sum of {num1} and {num2} is {sum_result}")

main()

We will then run the script from the terminal:

python example.py

When the script execution reaches the ipdb.set_trace() line, it will pause, and you will be dropped into the ipdb prompt. Here’s how you can interact with it:

ipdb> p a
3
ipdb> p b
4

The “p” command prints the values of “a” and “b” , which are “3” and “4” , respectively.

Another useful command is the “l” command when you run “l” at the ipdb prompt, you might see the output like this:

ipdb>
-> result = a + b
ipdb> l
1
2   def add_numbers(a, b):
3  ->     result = a + b
4      return result
5
6   def main():
7       num1 = 3
8       num2 = 4
9       sum_result = add_numbers(num1, num2)
10      print(f"The sum of {num1} and {num2} is {sum_result}")
11

In this output:

  • The -> symbol indicates the line where the debugger is currently paused.
  • The lines around this line are shown, giving you a broader context of the function and its operations.

This command lists the lines of code around the current line where the debugger has paused. By default, “l” displays 11 lines of code centered on the line where the execution is currently paused.

You can also specify a range of lines to view around the current line by providing arguments to the “l” command:

View Lines Before and After Current Line: Use “l start,end” to display lines from start to end. For example:

ipdb> l 1,10
  • This command lists lines 1 through 10 of the current file.
  • View Lines in a Specific Function or Module: If you want to focus on a specific function or module, you can use the “l” command in conjunction with “b” (breakpoint) commands to set breakpoints at specific lines, then list those areas.
  • Context: By viewing surrounding code, you gain context on how the current line fits into the larger codebase. This helps you understand how variables are being used and how different parts of the code interact.
  • Identify Issues: Seeing the lines before and after the breakpoint can help you identify logical errors, such as incorrect calculations or variable misuse.
  • Code Navigation: It assists in navigating through your code during a debugging session, especially if the function or file is long.

1. Setting Breakpoints

Breakpoints are markers you set in your code where execution will pause, allowing you to inspect the state of the program. You can set a breakpoint using the “b” (breakpoint) command in ipdb. For example, to set a breakpoint at a specific line number in a function or module:

ipdb> b 10

This sets a breakpoint at line 10 of the current file. You can also set a breakpoint at a specific function:

ipdb> b add_numbers

This sets a breakpoint at the start of the ”add_numbers” function.

2. Running the Code

After setting your breakpoints, run your script as usual. The execution will pause at each breakpoint you’ve set, allowing you to inspect and interact with the code at those points.

3. Listing Code Around a Breakpoint

Once the execution has paused at a breakpoint, you can use the “l” command to view the lines of code around the current line. This provides context on the code executing at that moment.

To move to the next line of code, use:

ipdb> n

The “n” command executes the current line (where result = a +b ) and moves to the next line.

If you want to run the program until it finishes or hits the next breakpoint, use command “c”. This command continues execution until the end of the program or the next breakpoint if there is one.

To stop debugging and exit the program, type “q” and the command quits the debugger and terminates the script.

Summary

In this simplified debugging session, we:

  • Used p to print the values of a and b.
  • Used l to list the source code around the breakpoint.
  • Used n to step to the next line of code.
  • Used c to continue execution until the program ends.
  • Used q to quit the debugger.

By practicing these basic commands, you’ll become more comfortable with ipdband better equipped to debug your Python code.

Conclusion

Using ipdb for debugging allows you to pause and inspect your code directly where it’s executing, making it more manageable and less daunting. It offers a more flexible and interactive experience compared to the standard Python shell, helping you understand and resolve issues more efficiently. By installing ipdb via Pipfile and using ipdb.set_trace(), you can gain valuable insights into your program’s behavior and improve your debugging skills.

Resources

[embed]GitHub - learn-co-curriculum/python-p3-debugging-with-ipdb Contribute to learn-co-curriculum/python-p3-debugging-with-ipdb development by creating an account on GitHub.github.com

[embed]Python Debugging With Pdb - Real Python In this hands-on tutorial, you'll learn the basics of using pdb, Python's interactive source code debugger. Pdb is a…realpython.com

[embed]ipdb IPython-enabled pdbpypi.org

[embed]Using ipdb to Debug Python Code - GeeksforGeeks A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and…www.geeksforgeeks.org


메타데이터
post_id
3d44f079f871
slug
a-beginners-guide-to-debugging-with-ipdb-set-trace-3d44f079f871
url
https://medium.com/@lindata/a-beginners-guide-to-debugging-with-ipdb-set-trace-3d44f079f871
canonical_url
https://medium.com/@lindata/a-beginners-guide-to-debugging-with-ipdb-set-trace-3d44f079f871
author_url
https://medium.com/@lindata
status
ok
fetched_at
2026-06-17 12:55:42