Python Debugging - Pretty Print Your Output

Debugging tools in any language you work with are super important to understand. They can help you find bugs in your code (I mean, they are “debugging” tools, right?), of course. But they can also be incredibly useful tools for learning. Learning about a new language or framework or even just trying to understand some code you didn’t write.

Here’s a real quick tip for debugging in Python.

For context let’s say we’re making a database call and getting back a whole pile of data. We are doing some data munging and want to make sure we’re doing the thing we intend. But it’s tricky to look at a blob of data in the console and suss out what’s going on. If we could just see the data formatted that’d help a ton.

Let’s use breakpoint and pprint to give us a hand.

First, throw a breakpoint() wherever you’d like your code execution to stop. This will halt the execution and all you to inspect your code at that point.

Execute your code and wait for the breakpoint to catch. You’ll see (Pub) prompt in your console when the breakpoint has been hit.

Import the pprint module by entering from pprint import pprint and press enter. If you don’t see an error you’ve imported that module into your console session.

Next use it. Maybe something like pprint(data_object) (where data_object is the thing we want a better look at).

Look at that nicely formatted output! Much easier to read.