Python Debugging Tools

Debugging is a vital part of software development. Python provides various tools to inspect, diagnose, and resolve issues in code effectively. Below are some essential debugging tools every Python developer should know.

Example 1: Using pdb

import pdb
x = 10
y = 20
pdb.set_trace()
print(x + y)

Example 2: Using breakpoint()

def divide(a, b):
  breakpoint()
  return a / b

print(divide(10, 2))

Example 3: Logging instead of print debugging

import logging
logging.basicConfig(level=logging.DEBUG)
x = 5
logging.debug(f"x = {x}")

Example 4: Using traceback to get error details

import traceback
try:
  1 / 0
except Exception as e:
  print("Error:", traceback.format_exc())

Example 5: Using warnings module

import warnings
warnings.warn("This is a warning message")

Example 6: Using assert to catch bugs early

def calculate_area(radius):
  assert radius > 0, "Radius must be positive"
  return 3.14 * radius ** 2

print(calculate_area(5))

Example 7: Using faulthandler for low-level crashes

import faulthandler
faulthandler.enable()

Example 8: Profiling with cProfile

import cProfile
def test():
  total = 0
  for i in range(1000):
    total += i
  return total

cProfile.run('test()')

Example 9: Memory profiling with memory_profiler

# Run using: mprof run script.py and then mprof plot
from memory_profiler import profile

@profile
def compute():
  a = [i for i in range(100000)]
  return sum(a)

compute()

Example 10: Line profiling with line_profiler

# Use kernprof -l script.py then python -m line_profiler script.py.lprof
@profile
def multiply():
  total = 1
  for i in range(1, 100):
    total *= i
  return total

multiply()