Python Debugging — Finding & Fixing Bugs
Debugging is the art of finding and fixing bugs. Python provides excellent tools for systematic debugging.
Learning Objectives
- Use pdb and breakpoint() for interactive debugging
- Apply logging for production debugging
- Use assertions for defensive programming
- Follow systematic debugging workflows
breakpoint() — Built-in Debugger
def calculate_discount(price, discount):
breakpoint() # Execution stops here
discounted = price * (1 - discount)
return discounted
# Commands in pdb:
# n (next) — execute next line
# s (step) — step into function
# c (continue) — run until next breakpoint
# p var — print variable
# l (list) — show source code
# q (quit) — exit debugger
Logging for Debugging
import logging
logging.basicConfig(level=logging.DEBUG)
def process_order(order_id):
logging.debug(f"Processing order {order_id}")
order = get_order(order_id)
logging.debug(f"Order details: {order}")
total = calculate_total(order)
logging.debug(f"Calculated total: {total}")
return total
Assertions
def divide(a, b):
assert b != 0, "Division by zero"
return a / b
def process_list(items):
assert isinstance(items, list), "Expected a list"
assert len(items) > 0, "List cannot be empty"
return sum(items) / len(items)
Systematic Debugging
# 1. Reproduce the bug
# 2. Read the error message carefully
# 3. Check the traceback
# 4. Print variable values
# 5. Simplify the code
# 6. Use debugger to step through
# 7. Check documentation
# 8. Search for similar issues
# 9. Fix and test
# 10. Add a test to prevent regression
Key Takeaways
- Use
breakpoint()for interactive debugging - Use
logginginstead of print for production code - Assertions catch bugs early in development
- Read error messages — they usually tell you what is wrong
- Simplify code to isolate the bug