Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pdb automatic pretty-printing

Tags:

python

pdb

I find myself doing this in pdb quite often:

import pprint
pprint.PrettyPrinter().pprint(variable_of_interest)

Is there a better way to pretty-print variables from pdb? I'm looking for something easier to type, and ideally something that's always available in pdb so I can use it anytime I'm debugging.

like image 411
nonagon Avatar asked Aug 15 '14 21:08

nonagon


People also ask

What is pdb set_trace ()?

pdb. set_trace(*, header=None) Enter the debugger at the calling stack frame. This is useful to hard-code a breakpoint at a given point in a program, even if the code is not otherwise being debugged (e.g. when an assertion fails). If given, header is printed to the console just before debugging begins.

What does import pdb pdb set_trace () do?

To start debugging within the program just insert import pdb, pdb. set_trace() commands. Run your script normally, and execution will stop where we have introduced a breakpoint. So basically we are hard coding a breakpoint on a line below where we call set_trace().

How do you set a breakpoint in Python pdb?

It's easy to set a breakpoint in Python code to i.e. inspect the contents of variables at a given line. Add import pdb; pdb. set_trace() at the corresponding line in the Python code and execute it. The execution will stop at the breakpoint.


2 Answers

In pdb documentation at the section Debugger Commands:

pp expression

Like the p command, except the value of the expression is pretty-printed using the pprint module.

like image 68
enrico.bacis Avatar answered Oct 15 '22 09:10

enrico.bacis


Like @enrico.bacis has mentioned pp can be used for pretty printing while using pdb.

(Pdb) pp your_var
like image 32
mrprofessor Avatar answered Oct 15 '22 09:10

mrprofessor