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 totalCommon 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 literalDebug 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 exceptionTip: Install icecream (pip install icecream) for better debug printing: ic(variable) prints variable name + value.