Debugging & Profiling
Find bugs fast, make slow code fast
A complete, practical guide to Python's debugging and profiling toolkit β reading tracebacks, stepping through code with pdb, measuring with timeit, and finding bottlenecks with cProfile and line_profiler.
import pdb def find_bug(numbers): total = 0 for n in numbers: pdb.set_trace() # execution pauses here total += n return total find_bug([1, 2, 3])
-> total += n
(Pdb) n
π Why Debugging and Profiling Are Skills
Two different questions, two different toolkits
Bugs and Bottlenecks Are Not the Same Problem
Debugging answers the question "why is this wrong?" It's about understanding what the code actually did versus what you expected it to do. The tools are tracebacks, breakpoints, print statements, logging, and a debugger you can step through.
Profiling answers the question "why is this slow?" It's about measuring where time is actually spent, not where you assume it's spent. The tools are timing, profilers, and line-level measurements β and they frequently reveal that the bottleneck is nothing like what you guessed.
Both skills share one principle: observe, don't guess. The most common debugging mistake is changing code based on a hunch without confirming the hunch. The most common profiling mistake is optimizing a function that was never the problem. Both are solved by looking at real data.
Everything here is built in
pdb, traceback, timeit, cProfile, and logging are all part of the standard library. Only line_profiler requires a third-party install, and it's optional.
- βRead a traceback confidently, from the bottom up
- βStep through code with
pdband inspect live state - βUse
breakpoint()as a portable debugging entry point - βLog instead of printing, and understand why
- βMeasure small pieces of code with
timeit - βFind hotspots with
cProfileand drill in withline_profiler
π Reading a Traceback
The error message is usually telling you exactly what's wrong
Read a traceback from the bottom up. The last line tells you the exception type and message. The frames above it show the call chain that led there, with the deepest call first.
def read_config(path): with open(path) as f: return f.read() def load_settings(): return read_config("missing.txt") def main(): load_settings() main()
File "traceback_example.py", line 11, in <module>
main()
File "traceback_example.py", line 9, in main
load_settings()
File "traceback_example.py", line 6, in load_settings
return read_config("missing.txt")
File "traceback_example.py", line 2, in read_config
with open(path) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
FileNotFoundError with the message No such file or directory: 'missing.txt' tells you the root cause immediately. The frames above are the context β they tell you where in your code that failure originated.
Chained exceptions
When an exception is raised while handling another, Python prints both β the most recent first, then the original. This is called exception chaining and it's one of the most useful parts of modern tracebacks.
def parse_age(raw): try: return int(raw) except ValueError as e: raise ValueError(f"invalid age: {raw!r}") from e parse_age("abc") # Traceback output shows: # ValueError: invalid age: 'abc' # # The above exception was the direct cause of the following exception: # # ValueError: invalid literal for int() with base 10: 'abc'
raise ... from e preserves the original error as context. Without it, the original is lost and you see only your wrapper message.
Getting a traceback as a string
import traceback try: 1 / 0 except ZeroDivisionError: text = traceback.format_exc() print(text) # Or capture the current call stack: import traceback print("".join(traceback.format_stack()))
traceback.format_exc() is the standard way to log an exception's full traceback. It's far more useful than logging just str(e).
Common exception types
| Exception | Typical cause | Fix |
|---|---|---|
TypeError | Wrong type passed | Check the argument type |
ValueError | Right type, invalid value | Validate before calling |
KeyError | Missing dict key | Use .get() or check membership |
AttributeError | Object lacks attribute | Check None, typo, or wrong object |
IndexError | Sequence index out of range | Check length before indexing |
FileNotFoundError | Path doesn't exist | Check path, use pathlib.Path.exists() |
π Stepping Through Code with pdb
Pause execution and inspect live state
The debugger lets you freeze time. When execution is paused, you can inspect variables, step line by line, go into function calls, and run arbitrary expressions in the current scope. This is far more powerful than scattering print() calls.
import pdb def apply_discount(price, percent): discount = price * (percent / 100) pdb.set_trace() # pause here return price - discount print(apply_discount(100, 20))
pdb commands you'll actually use
| Command | Shortcut | What it does |
|---|---|---|
next | n | Step to the next line in the current function |
step | s | Step into the next function call |
continue | c | Resume until the next breakpoint |
return | r | Run until the current function returns |
print | p | Evaluate an expression and print its value |
pp | β | Pretty-print a value (better for dicts/lists) |
list | l | Show surrounding source lines |
where | w | Show the call stack |
up / down | u / d | Move between stack frames |
quit | q | Exit the debugger and abort |
p len(numbers), p numbers[0], p type(x) β and see the result immediately. You can even call functions, though be careful of side effects.
Debugging after a crash
# Drop into the debugger at the point of an uncaught exception python -m pdb script.py # Or, post-mortem: debug the last exception that was raised import pdb try: risky_operation() except Exception: pdb.post_mortem() # inspect the state at the moment of failure
pdb.post_mortem() is invaluable in a try/except block or via the PYTHONBREAKPOINT environment variable when you want to inspect an exception after it happened.
βΈοΈ breakpoint() β The Portable Entry Point
Python 3.7+ gives you a built-in that respects your environment
breakpoint() is a built-in function that drops you into the debugger. By default it calls pdb.set_trace(), but you can change the debugger with the PYTHONBREAKPOINT environment variable β making your code work with the debugger you prefer.
def find_max(items): if not items: return None best = items[0] for item in items: if item > best: best = item return best print(find_max([3, 1, 4, 1, 5]))
# Add a breakpoint where you want to stop: def find_max(items): best = items[0] for item in items: breakpoint() # pauses here if item > best: best = item return best
| Environment value | Effect |
|---|---|
PYTHONBREAKPOINT=pdb.set_trace | Default β uses pdb |
PYTHONBREAKPOINT=ipdb.set_trace | Uses ipdb if installed |
PYTHONBREAKPOINT=pudb.set_trace | Uses pudb (terminal UI) if installed |
PYTHONBREAKPOINT=0 | Disables all breakpoints (useful in production) |
breakpoint() lets you commit debug hooks without forcing a specific debugger on every developer. Set PYTHONBREAKPOINT=0 in production to guarantee no accidental pauses.breakpoint() in code that runs in production. It will hang the process waiting for input. Either remove them before committing or ensure PYTHONBREAKPOINT=0 is set in the deployment environment.π Logging Instead of Printing
Diagnostic output you can turn on and off
print() debugging works, but it pollutes output and can't be filtered. The logging module gives you severity levels, timestamped output, configurable destinations, and the ability to silence everything without touching code.
import logging logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)s %(name)s: %(message)s", ) log = logging.getLogger(__name__) def process(items): log.debug("processing %d items", len(items)) for item in items: if item < 0: log.warning("skipping negative value: %s", item) continue log.info("processed %s", item) log.debug("done") process([1, 2, -1, 3])
Log levels
| Level | Numeric value | Use for |
|---|---|---|
DEBUG | 10 | Detailed diagnostic information |
INFO | 20 | Confirmation that things worked |
WARNING | 30 | Something unexpected but recoverable |
ERROR | 40 | A failure that prevented an operation |
CRITICAL | 50 | The program itself may not continue |
log.debug(...), you can silence it in production by setting the logger level to INFO. No code changes required. This is the single biggest advantage over print().
Logging exceptions with tracebacks
import logging log = logging.getLogger(__name__) try: risky_operation() except Exception: # exc_info=True appends the full traceback log.exception("operation failed") # Output includes the traceback automatically: # ERROR __main__: operation failed # Traceback (most recent call last): # ... # ValueError: something broke
log.exception() is log.error(..., exc_info=True) β use it inside an except block when you want the traceback captured.
Logging to a file
import logging logging.basicConfig( filename="app.log", level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", ) logging.info("application started")
For production, use RotatingFileHandler to cap file size and keep a few backups. A single log file that grows forever is its own kind of bug.
β±οΈ Measuring with timeit
Accurate timing for small pieces of code
A single time.time() call is not a reliable measurement. OS scheduling, garbage collection, and cache effects add noise. timeit runs code many times and reports the best or average result, which makes small differences visible.
import timeit # Compare two ways to build a list of squares setup = "n = 100" comprehension = timeit.timeit( "[i * i for i in range(n)]", setup=setup, number=10000, ) loop = timeit.timeit( """ result = [] for i in range(n): result.append(i * i) """, setup=setup, number=10000, ) print(f"comprehension: {comprehension:.4f}s") print(f"loop: {loop:.4f}s") print(f"speedup: {loop / comprehension:.2f}x")
Timing from the command line
# Time a single statement python -m timeit "-"-join(["a"] * 100) # With setup code python -m timeit -s "import random; data = list(range(1000))" "random.shuffle(data)" # Compare two implementations directly python -m timeit "sum(range(1000))" python -m timeit "sum(i for i in range(1000))"
timeit measures micro-operations. It's excellent for comparing two implementations of the same small task, but it won't tell you where a 5-second program spends its time. For that, you need a profiler.Interpreting the output
50000 loops, best of 5: 5.42 usec per loop
"Best of 5" is the fastest of five runs β that's the number closest to the true cost of the code, before noise from the operating system. Use the -r flag to increase repetitions.
π Finding Hotspots with cProfile
Measure the whole program, not one line at a time
cProfile records how long each function took and how many times it was called. It's the first tool to reach for when a program is slow β it tells you where to look before you start guessing.
import cProfile import pstats from io import StringIO def slow_sum(n): total = 0 for i in range(n): total += i return total def fast_sum(n): return sum(range(n)) def main(): for _ in range(100): slow_sum(10000) for _ in range(100): fast_sum(10000) profiler = cProfile.Profile() profiler.enable() main() profiler.disable() stream = StringIO() stats = pstats.Stats(profiler, stream=stream) stats.sort_stats("cumulative").print_stats(10) print(stream.getvalue())
What the columns mean
| Column | Meaning | How to read it |
|---|---|---|
ncalls | Number of calls | High count plus high time = candidate for optimization |
tottime | Time in the function itself | Excludes time in functions it calls |
percall | tottime / ncalls | Average cost per call |
cumtime | Cumulative time | Includes time in called functions |
filename:lineno | Where it lives | Jump straight to the code |
cumulative first, then by tottime. Cumulative time tells you which top-level operation is expensive. Tottime tells you which leaf function is doing the actual work. The bottleneck is usually a combination: a function with high cumulative time that calls a leaf with high tottime.
Profiling from the command line
# Profile an entire script python -m cProfile -s cumulative script.py # Save the profile to a file for later analysis python -m cProfile -o profile.out script.py # Open the saved profile in a text report python -c "import pstats; pstats.Stats('profile.out').sort_stats('cumulative').print_stats()"
Visualizing profiles
# Generate a flame graph with snakeviz
python -m pip install snakeviz
python -m cProfile -o profile.out script.py
snakeviz profile.out
Snakeviz opens a browser view showing the profile as an interactive flame graph. For large programs, this is far more readable than raw text output.
timeit to confirm the actual improvement.π¬ Line-Level Profiling
When a single function is the hotspot
cProfile tells you which function is slow. line_profiler tells you which line inside it is slow. Use it when you've already narrowed the problem to one function and need to know exactly where the time goes.
python -m pip install line_profiler
from line_profiler import LineProfiler def process_data(items): results = [] for item in items: value = item * 2 results.append(value) return results profiler = LineProfiler() profiler.add_function(process_data) profiler.enable_by_count() process_data(list(range(100000))) profiler.print_stats()
Total time: 0.018 s
File: line_profile_demo.py
Function: process_data at line 3
Line # Hits Time Per Hit % Time Line Contents
===============================================================
3 1 4.0e-06 4.0e-06 0.0% def process_data(items):
4 1 2.0e-06 2.0e-06 0.0% results = []
5 100001 1.2e-02 1.2e-07 66.7% for item in items:
6 100000 3.0e-03 3.0e-08 16.7% value = item * 2
7 100000 3.0e-03 3.0e-08 16.7% results.append(value)
8 1 1.0e-06 1.0e-06 0.0% return results
% Time column is the key. It shows what fraction of the function's time each line consumed. A line with 60%+ is where optimization effort will pay off. Lines with 0% are noise β leave them alone.
Using the @profile decorator
from line_profiler import profile @profile def expensive_function(data): return [x ** 2 for x in data] # Run with: # kernprof -l -v script.py
kernprof ships with line_profiler. The -l flag enables line profiling and -v prints the report. This is often easier than the programmatic API for one-off investigations.
When line_profiler is worth the install
- You've identified a single slow function with
cProfile - The function is long enough that the bottleneck isn't obvious
- You're about to micro-optimize and want to confirm the target first
For quick checks, cProfile is usually enough. line_profiler is for the moment when you know the function and need the line.
ποΈ Mini Project β Find and Fix a Slow Function
Put the whole workflow together
This example starts with a program that feels slow. We profile it, find the bottleneck, rewrite it, and measure the improvement β the exact sequence you'd follow on real code.
import cProfile import pstats from io import StringIO def build_squares_naive(n): result = [] for i in range(n): result.append(i * i) return result def build_squares_fast(n): return [i * i for i in range(n)] def run_naive(): for _ in range(200): build_squares_naive(5000) def run_fast(): for _ in range(200): build_squares_fast(5000) def profile(fn, label): profiler = cProfile.Profile() profiler.enable() fn() profiler.disable() stream = StringIO() stats = pstats.Stats(profiler, stream=stream) stats.sort_stats("tottime") stats.print_stats(3) print(f"--- {label} ---") print(stream.getvalue()) profile(run_naive, "naive") profile(run_fast, "fast")
The profile output will show build_squares_naive with a much higher tottime than build_squares_fast. That's the confirmation you need before rewriting: the bottleneck is exactly where you suspected, and the list comprehension genuinely removes it.
cProfile, (3) sort by tottime, (4) find the function with the largest share, (5) drill in with line_profiler if needed, (6) change one thing, (7) measure again. Never skip step 2.
β Frequently Asked Questions
Common questions about debugging and profiling
print() is fine for quick checks and for understanding the flow of a small script. A debugger is better when you need to inspect complex state, step through branching logic, or understand why a value became what it is. As a rule: if you find yourself adding more than two prints to investigate one bug, switch to pdb.
breakpoint() is a built-in that respects the PYTHONBREAKPOINT environment variable. By default it calls pdb.set_trace(), but you can redirect it to ipdb, pudb, or disable it entirely with PYTHONBREAKPOINT=0. It's the modern, portable entry point.
Start with cProfile β it's built in and tells you which functions are slow. Once you've found a specific function, use line_profiler to see which lines inside it consume time. Don't install line_profiler until you've confirmed the function with cProfile.
Profilers add instrumentation overhead to every function call. The absolute times in a profile are inflated β sometimes by 2β3x. The relative numbers are what matter: they show which functions are expensive compared to each other. After optimizing, measure the actual improvement with timeit or by timing the real program.
Don't use an interactive debugger in production β it will hang the process. Instead, rely on structured logging, exception tracebacks captured via log.exception(), and error monitoring. If you need breakpoint() in code that might run in production, make sure PYTHONBREAKPOINT=0 is set in the deployment environment.
Send SIGQUIT (Ctrl+\) on Unix, or use faulthandler.dump_traceback_later(timeout), which prints all thread stacks if the program runs longer than expected. In containers, you can also attach with py-spy to see live stacks without stopping the process.
cProfile only profiles the thread it runs in. For multithreaded code, use py-spy or yappi, which handle per-thread profiling. For async code, py-spy shows you the event loop and any tasks that are blocked. In general, asyncio's own debug mode (asyncio.run(main(), debug=True)) surfaces slow callbacks.
No. Profile first, then optimize only the functions that show up at the top of the list. The classic mistake is spending an hour optimizing a function that accounts for 2% of runtime. Amdahl's law is unforgiving: a 10x speedup on 2% of the runtime saves 1.8% overall.
π Where to Go Next
Keep building on what you just learned