Wednesday, November 12, 2025

thumbnail

Debugging Your Full Stack Python Application with PDB

 🧠 What is PDB?


PDB stands for Python Debugger, a built-in interactive tool that helps you inspect your code step by step, check variable values, and find where errors occur.


It’s part of Python’s standard library — no installation needed.


You can use it in any Python project, including:


Backend code (Django, Flask, FastAPI)


API calls


Command-line tools


Scripts


Even inside tests


🧩 Why Use PDB?


PDB helps you:


Pause code execution anywhere.


Inspect variable values and object states.


Step through code line by line.


Find bugs faster than adding dozens of print() statements.


⚙️ Basic Usage of PDB

1. Insert a Breakpoint


You can pause your program by adding this line:


import pdb; pdb.set_trace()



Or, in Python 3.7+, you can use the cleaner built-in function:


breakpoint()



When your program reaches this line, it will pause and open an interactive debugging console in your terminal.


2. PDB Commands You Should Know

Command Description

n Next – Run the next line of code.

s Step into – Enter into a function being called.

c Continue – Continue running until the next breakpoint.

l List – Show where you are in the code.

p <var> Print – Display the value of a variable.

q Quit – Exit the debugger.

h Help – Show available commands.

🧩 Example 1: Debugging a Simple Python Function

def divide(a, b):

    result = a / b

    return result


def main():

    x = 10

    y = 0

    breakpoint()  # Pause execution here

    print(divide(x, y))


if __name__ == "__main__":

    main()



When you run this script:


python app.py



You’ll enter the PDB console at the breakpoint() line:


> app.py(9)main()

-> print(divide(x, y))

(Pdb)



You can now:


(Pdb) p x

10

(Pdb) p y

0



If you continue (c), you’ll trigger a ZeroDivisionError — confirming the bug.


🧩 Example 2: Debugging Django Views


You can use breakpoint() inside Django views, forms, or models.


Example:


# views.py

from django.shortcuts import render

from .models import Product


def product_list(request):

    products = Product.objects.all()

    breakpoint()  # Debug here

    return render(request, 'products.html', {'products': products})



When you visit the page in your browser (e.g., /products), the Django server will pause execution and drop into PDB in your terminal.


Then, you can check variables like this:


(Pdb) p products

<QuerySet [<Product: Book>, <Product: Phone>]>



You can even query data directly:


(Pdb) Product.objects.filter(price__gt=50)

<QuerySet [<Product: Phone>]>



💡 Tip: Use runserver --noreload when debugging with breakpoints in Django.


python manage.py runserver --noreload



Otherwise, the debugger might run twice because Django reloads code automatically.


🧩 Example 3: Debugging Flask or FastAPI Apps


Flask:


from flask import Flask


app = Flask(__name__)


@app.route('/')

def home():

    message = "Hello, Flask!"

    breakpoint()

    return message



Run the app and open / in your browser — the terminal will drop into PDB so you can inspect message or the request context.


🧩 Example 4: Debugging Inside Unit Tests


You can also use breakpoint() inside Django or unittest tests:


from django.test import TestCase

from myapp.models import Product


class ProductTest(TestCase):

    def test_discount(self):

        p = Product.objects.create(name="Book", price=100)

        discounted = p.discount_price(10)

        breakpoint()

        self.assertEqual(discounted, 90)



When running:


python manage.py test



The test runner will pause at the breakpoint, letting you inspect the test environment.


🧠 Advanced PDB Tips

1. Use Conditional Breakpoints


You can set a breakpoint that only triggers under certain conditions:


if user.is_admin:

    breakpoint()


2. Use pdb from the Command Line


You can start debugging without modifying code:


python -m pdb myscript.py


3. Post-Mortem Debugging (after an error)


You can inspect variables after a crash:


python -m pdb -c continue myscript.py



or inside an exception handler:


import pdb, sys

try:

    risky_function()

except Exception:

    pdb.post_mortem(sys.exc_info()[2])


🧩 Example: Debugging a Full Stack Flow


Let’s say you have a Django REST API that calls a third-party service and stores the response in the database.


You can set breakpoint() in the API view to inspect request data.


Add another in the service layer to inspect API responses.


Finally, one in the model save() method to confirm data is stored correctly.


This way, you can follow the entire flow:

Frontend → API endpoint → Business logic → Database layer.


⚙️ Integrating PDB with VS Code or PyCharm


Most IDEs support PDB integration:


VS Code: Add a breakpoint with the red dot and start the Python Debugger.


PyCharm: Use the “Debug” button instead of “Run”.

Both tools give you a graphical interface for inspecting variables and stepping through code.


🧭 Summary

Concept Description

Tool PDB (Python Debugger)

Purpose Pause, inspect, and step through code execution

Insert import pdb; pdb.set_trace() or breakpoint()

Useful In Scripts, Django/Flask apps, unit tests, API debugging

Bonus Tip Use --noreload in Django to avoid duplicate breakpoints

Learn Fullstack Python Training in Hyderabad

Read More

Test-Driven Development (TDD) with Python and Django

Writing Unit Tests for Django Projects

Introduction to Unit Testing in Python

Testing and Debugging in Python

At Our Quality Thought Training Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive