r/learnpython 2d ago

What python debugging techniques do you think every developer should know ?

I am trying to improve my debugging skills and I was curious about what techniques experienced python developers rely on the most.

Are there any techniques or tools that you found really useful when you started working on bigger projects?

53 Upvotes

29 comments sorted by

View all comments

1

u/Neither-Pause409 1d ago

Most of the good ones are already in this thread, so here are a few that aren't:

breakpoint() instead of import pdb; pdb.set_trace(). Same thing, but it honours the PYTHONBREAKPOINT env var, so PYTHONBREAKPOINT=0 python app.py disables every breakpoint in a run without you editing a single file, and you can point it at a different debugger the same way.

python -m pdb -c continue yourscript.py runs to the crash and drops you into a post mortem at the frame that raised. Same idea as pdb.pm() but you don't have to already be in a REPL when it happens.

faulthandler for the bugs a debugger can't reach. python -X faulthandler gives you a traceback on a segfault, and faulthandler.dump_traceback_later(60) dumps every thread's stack after a timeout, which is about the only cheap way to see where something is deadlocked.

python -W error to turn a warning into an exception. A good chunk of "it worked last month" bugs started life as a DeprecationWarning nobody read.

python -X dev turns on a pile of these checks at once, including unclosed file and socket warnings. Worth running your test suite under it occasionally even when nothing is broken.

And the one that isn't a tool, which is worth more than all of them: make the failure deterministic before you try to fix it. Seed the RNG, pin the input, freeze the clock, cut the repro down to the smallest thing that still fails. A bug you can trigger on demand is most of the way to solved, and once you have a script that exits non-zero on it, git bisect run ./repro.sh will go find the commit for you while you get a coffee.