Python Debugger – Python pdb
Last Updated :
04 Nov, 2022
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line, thereby making it great for debugging code on remote servers when we don’t have the privilege of a GUI-based debugger.
pdb supports:
- Setting breakpoints
- Stepping through code
- Source code listing
- Viewing stack traces
Starting Python Debugger
There are several ways to invoke a debugger
- To start debugging within the program just insert import pdb, pdb.set_trace() commands. Run your script normally, and execution will stop where we have introduced a breakpoint. So basically we are hard coding a breakpoint on a line below where we call set_trace(). With python 3.7 and later versions, there is a built-in function called breakpoint() which works in the same manner. Refer following example on how to insert set_trace() function.
Example1: Debugging a Simple Python program of addition of numbers using Python pdb module
Intentional error: As input() returns string, the program cannot use multiplication on strings. Thus, it’ll raise ValueError.
Python3
import pdb
def addition(a, b):
answer = a * b
return answer
pdb.set_trace()
x = input("Enter first number : ")
y = input("Enter second number : ")
sum = addition(x, y)
print(sum)
|
Output :

set_trace
In the output on the first line after the angle bracket, we have the directory path of our file, line number where our breakpoint is located, and <module>. It’s basically saying that we have a breakpoint in exppdb.py on line number 10 at the module level. If you introduce the breakpoint inside the function, then its name will appear inside <>. The next line is showing the code line where our execution is stopped. That line is not executed yet. Then we have the pdb prompt. Now to navigate the code, we can use the following commands :
| Command |
Function |
| help |
To display all commands |
| where |
Display the stack trace and line number of the current line |
| next |
Execute the current line and move to the next line ignoring function calls |
| step |
Step into functions called at the current line |
Now, to check the type of variable, just write whatis and variable name. In the example given below, the output of type of x is returned as <class string>. Thus typecasting string to int in our program will resolve the error.
Example 2: Checking variable type using pdb ‘whatis’ command
We can use ‘whatis‘ keyword followed by a variable name (locally or globally defined) to find its type.
Python3
a = 20
b = 10
s = 0
for i in range(a):
s += a / b
b -= 1
|

Finding variable type using whatis command in pdb
- From the Command Line: It is the easiest way of using a debugger. You just have to run the following command in terminal
python -m pdb exppdb.py (put your file name instead of exppdb.py)
This statement loads your source code and stops execution on the first line of code.
Example 3: Navigating in pdb prompt
We can navigate in pdb prompt using n (next), u (up), d (down). To debug and navigate all throughout the Python code, we can navigate using the mentioned commands.
Python3
a = 20
b = 10
s = 0
for i in range(a):
s += a / b
b -= 1
|
Output :

Navigate in pdb prompt using commands
Example 4: Post-mortem debugging using Python pdb module
Post-mortem debugging means entering debug mode after the program is finished with the execution process (failure has already occurred). pdb supports post-mortem debugging through the pm() and post_mortem() functions. These functions look for active trace back and start the debugger at the line in the call stack where the exception occurred. In the output of the given example, you can notice pdb appear when an exception is encountered in the program.
Python3
def multiply(a, b):
answer = a * b
return answer
x = input("Enter first number : ")
y = input("Enter second number : ")
result = multiply(x, y)
print(result)
|
Output :
Checking variables on the Stack
All the variables including variables local to the function being executed in the program as well as global are maintained on the stack. We can use args(or use a) to print all the arguments of a function which is currently active. p command evaluates an expression given as an argument and prints the result.
Here, example 4 of this article is executed in debugging mode to show you how to check for variables :

checking variable values
Python pdb Breakpoints
While working with large programs, we often want to add a number of breakpoints where we know errors might occur. To do this you just have to use the break command. When you insert a breakpoint, the debugger assigns a number to it starting from 1. Use the break to display all the breakpoints in the program.
Syntax:
break filename: lineno, condition
Given below is the implementation to add breakpoints in a program used for example 4.

Adding_breakpoints
Managing Breakpoints
After adding breakpoints with the help of numbers assigned to them, we can manage the breakpoints using the enable and disable and remove command. disable tells the debugger not to stop when that breakpoint is reached, while enable turns on the disabled breakpoints.
Given below is the implementation to manage breakpoints using Example 4.

Manage_breakpoints
Similar Reads
Python JSON
Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called JSON. This package provides all the necessary tools for working with JSON Objects i
3 min read
Python - Pretty Print JSON
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will learn about JSON pretty print What is JSON?JSON (JavaScript Object Notation) is a text-based data format that is
5 min read
Convert Generator Object To JSON In Python
JSON (JavaScript Object Notation) is a widely used data interchange format, and Python provides excellent support for working with JSON data. However, when it comes to converting generator objects to JSON, there are several methods to consider. In this article, we'll explore some commonly used metho
2 min read
Flattening JSON objects in Python
JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This
3 min read
Node.js keyObject.export([options]) Method
The export method in NodeJS allows you to create a JSON representation of an object or array. This can be useful for storing data in a file or for sending data over the network. The options argument allows you to control the output of the JSON string, such as by adding indentation. Syntax: The synta
2 min read
jQuery getJSON() Method
In this article, we will learn about the getJSON() method in jQuery, along with understanding their implementation through the example. jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do
2 min read
How to JSON Decode in PHP?
JSON Decode is the process of converting a JSON string into a PHP variable, typically an object or an associative array. Then we will print that decode JSON text. Below are the approaches to JSON decoding in PHP: Table of Content Using json_decode() methodUsing Explode and Foreach LoopUsing json_dec
2 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parame
2 min read
Python - Convert list of dictionaries to JSON
In this article, we will discuss how to convert a list of dictionaries to JSON in Python. Python Convert List of Dictionaries to JsonBelow are the ways by which we can convert a list of dictionaries to JSON in Python: Using json.dumps()Using json.dump()Using json.JSONEncoderUsing default ParameterDi
5 min read
How to Convert Blob Data to JSON in JavaScript ?
When dealing with Blob data in JavaScript, such as binary data or files, we may need to convert it into JSON format for doing so JavaScript provides us with various methods as listed below. Table of Content Using FileReader APIUsing TextDecoder APIUsing FileReader APIIn this approach, we first use t
2 min read
How to Encode Array in JSON PHP ?
Encoding arrays into JSON format is a common task in PHP, especially when building APIs or handling AJAX requests. Below are the approaches to encode arrays into JSON using PHP: Table of Content Using json_encode()Encoding Associative ArraysCustom JSON SerializationUsing json_encode()PHP provides a
2 min read
How to Copy Array by Value in JavaScript ?
There are various methods to copy array by value in JavaScript. 1. Using Spread OperatorThe JavaScript spread operator is a concise and easy metho to copy an array by value. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array. Synt
4 min read
Mongoose Document.prototype.toJSON() API
The Mongoose Document API.prototype.toJSON() method of the Mongoose API is used on the Document model. It allows to convert the result set into JSON object. The converted JSON object then can be used as a parameter to the JSON.stringify() method. Let us understand the toJSON() method using an exampl
3 min read
How to open JSON file ?
In this article, we will open the JSON file using JavaScript. JSON stands for JavaScript Object Notation. It is basically a format for structuring data. The JSON format is a text-based format to represent the data in form of a JavaScript object. Approach: Create a JSON file, add data in that JSON f
2 min read
How to open json file ?
JSON (JavaScript Object Notation) is a lightweight, text-based data format that stores and exchanges data. Let's see how we can create and open a JSON file. How to Create JSON Files?Before learning how to open a JSON file, it's important to know how to create one. Below are the basic steps to create
2 min read
Read, Write and Parse JSON using Python
JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON. Example of JSON String s = '{"id":0
4 min read
How to Convert CSV to JSON in JavaScript ?
In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We'll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in J
3 min read
How to Convert JSON to Blob in JavaScript ?
This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data. What is JSON and Blob?JSON (JavaScript Object Notation): A light
2 min read
How to Convert Hash to JSON in Ruby?
Ruby Hash is an unordered set of data in key-value pairs. These are mutable and can store multiple data types. JSON stands for Javascript Object Notation and is a human-readable file format that is commonly used in web services and API calls. In this article, we will discuss how to convert a hash to
2 min read