Ad – 728Γ—90
πŸ› Real-World

Python Debugging – pdb & Debugging Techniques

Debugging is half of programming. Python provides pdb, breakpoint(), and rich tracebacks. Learn to read errors fast and squash bugs systematically.

⏱️ 20 min read🎯 Real-WorldπŸ“… Updated 2026

Reading Tracebacks

Python
# Read tracebacks BOTTOM to TOP
# Bottom = actual error, Top = call entry point

def calculate(data):
    return sum(data) / len(data)

calculate([])  # ZeroDivisionError

# Traceback (most recent call last):
#   File "app.py", line 6, in 
#     calculate([])
#   File "app.py", line 2, in calculate
#     return sum(data) / len(data)
# ZeroDivisionError: division by zero

breakpoint() – Interactive Debugger

Python
def process_order(order):
    total = 0
    for item in order["items"]:
        breakpoint()  # Execution pauses here
        # pdb commands: n=next, s=step, c=continue, p x=print, q=quit
        total += item["price"] * item["qty"]
    return total

Common Error Types

Python
# NameError – variable doesn't exist
print(x)            # NameError: name 'x' is not defined

# TypeError – wrong type
"2" + 2             # TypeError: can only concatenate str to str

# KeyError – dict key missing
d = {"a": 1}
d["b"]              # KeyError: 'b'
d.get("b", None)    # Safe alternative

# AttributeError – bad attribute
None.upper()        # AttributeError: 'NoneType' has no attribute 'upper'

# IndexError – out of range
[1, 2][5]           # IndexError: list index out of range

# ValueError – right type, bad value
int("abc")          # ValueError: invalid literal

Debug Techniques

Python
# f-string debugging (Python 3.8+)
x = compute_something()
print(f"{x=}")           # prints: x=42

# Early assertions
assert isinstance(data, list), f"Expected list, got {type(data)}"
assert len(data) > 0, "Data cannot be empty"

# Post-mortem in shell
import pdb; pdb.pm()    # after uncaught exception
Tip: Install icecream (pip install icecream) for better debug printing: ic(variable) prints variable name + value.