Python Debugging With Pdb Tutorial – Complete Guide

Debugging is an essential part of software development but is often seen as challenging by beginners. Our journey today covers a valuable tool in the Python ecosystem designed just for this – Python Debugger, or as it is popularly known, ‘pdb’.

What is pdb?

‘pdb’ is a built-in Python module used as a debugging tool by developers. Although Python has several such tools, pdb stands out due to its simplicity and accessibility. It offers interactive debugging, allowing us to thoroughly inspect our code, control its execution flow, and determine the root of our bugs.

Why Should You Learn pdb?

While some might argue that print statements or advanced IDEs could suffice for debugging, learning pdb provides unique benefits:

  • It’s inbuilt: Since Python ships with pdb, you don’t need to install anything else.
  • It’s interactive: pdb allows you to control the flow of your code execution with different commands, making debugging more manageable.
  • It’s universal: Regardless of your development environment, pdb works the same way, making it a reliable tool to debug Python code anywhere.

Despite these advantages, many developers are unfamiliar with this powerful tool. This tutorial aims to get you comfortable with pdb, making your coding journey smoother and more efficient.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Using pdb – Step by Step

Now that you have a basic understanding of what pdb is and its benefits, let’s see it in action with a few examples. We’ll start with the simplest usage and gradually explore more functionalities.

Basic Debugging

First off, let’s see how to integrate pdb into our Python code. We’ll start by creating a simple addition function, and insert pdb inside it.

import pdb

def add(x, y):
    pdb.set_trace()
    result = x + y
    return result

print(add(2, 3))

When you run this function, the pdb interactive debugger is invoked at the point where you inserted pdb.set_trace() and pauses the execution.

Interactive Debugging

After pdb pauses execution, you use commands to control the program flow. The n (next) command executes the next line of code.

(Pdb) n

If you hit n again, pdb will execute the following line and prepare to return the function result.

Getting Variable Value

In pdb, querying a variable’s value is as simple as typing the variable name:

(Pdb) x
2
(Pdb) y
3
(Pdb) result
5

Continuing Execution

When you’re done inspecting and wish to continue execution till the next breakpoint or till the end of the program, you can use the c (continue) command:

(Pdb) c

In this case, since we only had one breakpoint, using c will end the program.

Jumping to a Specific Line

With the “jump” (“j”) command, you can make execution jump to a specified line number. This skips all the lines in-between:

import pdb

def two_additions(x, y):
    pdb.set_trace()
    result1 = x + y
    result2 = 2 * (x + y)
    return result1, result2

print(two_additions(2, 3))
(Pdb) j 8

This will skip line 6 and jump to line 8, which executes the second addition.

These commands are fundamental to pdb’s operation and a good starting point to grasp its power in debugging. We’ll delve deeper into additional functionalities in the next section.

Digging Deeper into pdb

Having grasped the basics, let’s delve deeper and uncover more of pdb’s capabilities that will ease your debugging process.

Stepping into functions

If you want the execution to enter a called function, you can use the s (step) command.

import pdb

def add(x, y):
    return x + y

def multiply_by_two(x, y):
    pdb.set_trace()
    result = add(x, y)
    return 2 * result

print(multiply_by_two(2, 3))
(Pdb) s

The execution will now enter the add function.

Printing expressions

Similar to getting a variable value, pdb can also evaluate and print expressions. Let’s try out the p (print) command:

(Pdb) p x+y
5

Breaking at a specific condition

At times, we want the execution to break not only at a specific point but also when a certain condition is met. pdb accommodates this with the b (break) command:

import pdb

def add_and_multiply(x, y):
    pdb.set_trace()
    result1 = x + y
    result2 = 2 * (x + y)
    return result1, result2

for i in range(10):
    print(add_and_multiply(i, 2*i))

(Pdb) b 6, x==5

pdb will now only pause if x is equal to 5 when it’s at line 6.

List source code

With pdb, you can list the source code around the current line of execution. This helps see what part of the code you’re currently at:

(Pdb) l

You’ll see a snippet of the source code around the current execution.

Catch exceptions

Last but certainly not least, you can make pdb catch unhandled exceptions by invoking it post-mortem:

import pdb

def faulty_function(x):
    return 5 / x

try:
    print(faulty_function(0))
except Exception:
    pdb.post_mortem()

The debugger will be entered when an unhandled exception occurs in the try block.

pdb is powerful and helps Python programmers debug effectively. Use these examples as your learning sandbox, boost your knowledge of pdb, and save countless hours while debugging!

Where to Go Next

Now that you’ve dipped your toes into the world of Python debugging with pdb, you’re probably wondering where to go from here. We’re thrilled to see how far you’ve progressed and we offer numerous resources to support your journey ahead. We would first recommend you to keep practicing with pdb. Get comfortable with the commands, understand their flow, and soon enough, you’ll find debugging Python code much smoother and quicker.

Next up, expanding your Python knowledge. pdb is just one tool of the many that Python has to offer. There’s a lot more to explore and master. To support your learning, we at Zenva offer a comprehensive course called the Python Mini-Degree.

The Python Mini-Degree is an exhaustive suite of courses, covering Python from the basics to more advanced topics. The curriculum touches on algorithms, object-oriented programming, and even ventures into game and app development with popular Python libraries. Whether an absolute beginner or an advanced learner, you’ll find these courses a thrilling part of your Python journey.

What makes the Python Mini-Degree and other Zenva courses special is our focus on professional-level content. We help learners of all skill levels to boost their technical skills, enrich their portfolio, and thereby, their career opportunities. With over 250 courses available, ranging from game development to AI, we are truly a one-stop solution for learning coding online, at your pace.

If you’re looking to dive into a specific area of Python, we also offer a broad collection of focused Python courses.

Conclusion

Debugging doesn’t need to be the daunting task it’s often made out to be. With pdb, one of the most reliable and straightforward tools in Python’s belt, you can conquer your bugs and swiftly fix your errors. As you’ve seen throughout this tutorial, getting started with pdb isn’t challenging. An interactive debugger like this could be the key to unlocking your programming potential and saving countless hours often spent in trial and error.

There’s a lot more to explore and master in Python, and we’re here to help you every step of the way. Our comprehensive Python Mini-Degree is flawlessly designed to take you from a beginner to a Python ace. Get started today and see where the exciting world of Python takes you!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.