practical Python
debugging
kevin@freshbooks.com
agenda
- Debugging
- Intro to pdb
- variable inspection
- execution control
- stack frame movement
- breakpoints
- custom aliases
- Alternatives to pdb
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it
- Brian W. Kernighan
intro to pdb
- Included in the standard lib
- Modes of operation
- run, script, post-mortem mode
- trace mode
- All these modes drop you into a pdb prompt
- You can
- Inspect
- Control
- Move
INSPECTION COMMANDS
- p(rint) - print value of variable
- display - "watch" the value of a variable
- a(rgs) - arguments of the current function
- r(v) - the return value of the last function
- l(ist) - where in the source code am I?
Execution control commands
- s(tep) - Step into the function
- n(ext) - Step over the function
- r(eturn) - Return from the function
- until - Useful for breaking out of a loop
- c(ontinue) - Continue execution
stack Frame control commands
- w(here) - where in the stack am I?
- u(p) - move up the stack frame
- d(own) - move down the stack frame
Custom aliases
- Use the `alias` command
alias nl n;;l
alias sl s;;l
- $HOME/.pdbrc
breakpoints
alternatives to pdb
- pdb++
- pudb
- ipdb
- debug
pdb++
# install
pip install pdbpp
# usage
import pdb; pdb.set_trace()
- drop-in replacement of pdb
- tab-completion
- syntax colouring
ipdb
# install
pip install ipdb
pip install debug
# usage
import ipdb; ipdb.set_trace()
# or
import debug # yeah, that's it!
- uses ipython
- tab-completion
- syntax colouring
pudb
# install
pip install pudb
# usage
import pudb; pudb.set_trace()
- Console "GUI" debugger
- uses libncurses
- Very handy for navigating unfamiliar code
Questions?
PP - Debugging
By Kevin Jing Qiu
PP - Debugging
- 873