Using ipdb to Debug Python Code
Last Updated :
17 Jun, 2024
Interactive Python Debugger(IPDB) is a powerful debugging tool that is built on top of the IPython shell. It allows developers to step through their code line by line, set breakpoints, and inspect variables in real-time. Unlike other debuggers, IPDB runs inside the Python interpreter, which makes it easier to use and integrate with other tools.
Required Modules
pip install ipdb
How to use IPDB
After the debugger is installed, now you can start using IPDB by adding the following line of code:
import ipdb;
#code
ipdb.set_trace()
This line of code will set a breakpoint in your code at the point where it is executed. When the code reaches this point, the debugger will pause execution and drop you into an interactive shell where you can start debugging.
From here, you can use various IPDB commands to step through your code, inspect variables, and more. Some of the most commonly used commands include:
command
| keyword
| function
|
next
| n
| Execute the current line and move to the next one
|
step
| s
| Step into the function call on the current line
|
continue
| c
| Continue execution until the next breakpoint or the end of the program
|
print
| p
| Print the value of a variable
|
quit
| q
| Quit the debugger
|
Examples
Iterating through the loop
The function factorial(n), which is defined in this code, uses recursion to get the factorial of a given integer n. In this case, the method returns 1 if n is less than or equal to 0. If not, it calls itself recursively with n-1 as the argument and multiplies the outcome by n. After the factorial() function declaration, the code additionally places a breakpoint using ipdb.set_trace().
Python
import ipdb
def factorial(n):
if n <= 0:
return 1
else:
return n * factorial(n-1)
ipdb.set_trace()
num = 5
fact = factorial(num)
print("Factorial of", num, "is", fact)
Output :
the terminal will open like this and you can control the compiler using commands
giving 'n' command, execution will be taken to the next breakpoint
'p' command will print the value of the variable i.e. 'num'
's' step into the function call on the current line
'c' takes to the next breakpoint or end of the programViewing sorting program
Sort_numbers() and main() are two functions defined in this code. sort_numbers() takes a list of numbers as input, uses ipdb.set_trace() to set a breakpoint, uses the sorted() function to sort the numbers in descending order, and then returns the sorted list.
Python
import ipdb
def sort_numbers(numbers):
ipdb.set_trace()
sorted_numbers = sorted(numbers, reverse=True)
return sorted_numbers
def main():
numbers = [5, 2, 8, 1, 9, 4]
sorted_numbers = sort_numbers(numbers)
print(sorted_numbers)
main()
Output:
When we run the code again, we'll see that it pauses at the breakpoint, and we can use various IPDB commands to examine the state of the program. For example, we can use the print command to check the value of the numbers argument :
IPDB exampleSimple multiply and add the program
In this code, we are using the ipdb.set_trace() instruction, the code places a breakpoint. When this happens, the Python debugger will halt the program's execution at that particular moment to allow the user to investigate the status of the program at that time. Following the breakpoint, the program executes add(), passing result1 and y as inputs, and saving the outcome in result2. The value of result2 is finally written to the console.
Python
import ipdb
def multiply(x, y):
result = x * y
return result
def add(x, y):
result = x + y
return result
def main():
x = 5
y = 10
result1 = multiply(x, y)
ipdb.set_trace() #breakpoint created by ipdb
result2 = add(result1, y)
print(result2)
main()
Output :
IPDB exampleDifference between pdb debugger and ipdb debugger
Both PDB and IPDB support column-based debugging, which means that you can set a breakpoint at a specific column in a line of code. However, IPDB offers some additional functionality that makes it more user-friendly and powerful than PDB.
features Â
|   pdb  Â
|  ipdb   Â
|
---|
User Interface
| - No syntax highlighting Â
- No tab-completion.
- Don't allow customization
| Â
- Syntax highlighting
- Tab-completion.
- Allows you to customize the way that your debugger display looks
Â
|
Additional Features
| Limited additional features beyond basic debugging capabilities.
| Additional features such as post-mortem debugging and the ability to set breakpoints at specific columns.
|
Installation
| Included Python by default.
| Needs to be installed separately using pip.
|
Compatibility          Â
| Compatible with IPDB.
| Fully compatible with PDB
|
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Support Vector Machine (SVM) Algorithm Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read