Debugging Python Code

To my knowledge there are two main approaches to debugging some Python code in Emacs.

Using M-x pdb

M-x pdb |*gud-test*        x                                 [37%] 15:41 21/06/25 ☰ -> if not state.headers_complete:                                           (Pdb)  > /var/home/alex/Projects/swyddfa/lsp-devtools/develop/lib/lsp-devtools/ls\ p_devtools/agent/server.py(166)feed()                                       -> if (idx := state.buffer.find(SEP)) == -1:                                (Pdb)  > /var/home/alex/Projects/swyddfa/lsp-devtools/develop/lib/lsp-devtools/ls\ p_devtools/agent/server.py(169)feed()                                       -> line, state.buffer = state.buffer[:idx], state.buffer[idx + len(SEP) :]  (Pdb) idx 30                                                                          (Pdb)  -  *gud-test* 25:6      (Debugger:run Apheleia)                             +  158 # messages to be stuck in the buffer... +  159 # +  160 # So we will keep running that parser as long as the buffe\ r continues toshrink +  161 previous_length = len(state.buffer) + 1                     +  162 whilelen(state.buffer) < previous_length:                  +  163 previous_length = len(state.buffer)                     +  164 breakpoint()                                            +  165 ifnot state.headers_complete:                          +  166 if (idx := state.buffer.find(SEP)) == -1:           +  167 return +  168  + =>169 line, state.buffer = state.buffer[:idx], state.buf\ -🖿 lsp-devtools server.py 169:0      (Python Flymake[001] ws Apheleia© 

Emacs supports Python’s built-in pdb debugger out of the box thanks to the Grand Unified Debugger.

Since everything is avaialable out of the box, there’s nothing really to setup! Just run M-x pdb, Emacs will ask you how you want to invoke pdb

Run pdb (like this): python -m pdb

Which you can of course modify to run your code. What’s cool about this is that it can be any python command that eventually results in a pdb session.

For example, I often will pass the --pdb flag to pytest to conduct a post-mortem on a particular test case, this will just workTM with Emacs’ pdb command!

Run pdb (like this): hatch test -i py=3.11 -i sphinx=8 -- tests/example/test_example.py::test_this --pdb

Breakpoints can be added by adding a call to the built-in breakpoint() function.

Using dape

TODO

Figure out how to use this.