Iterating Faster with PDB and Flask

Flask is a great Python web framework that makes it faster and easier to build out ideas and design concepts, with just a few lines of code. One trick that has made that even easier is using the Python debugger, PDB, to help write application code.

Drop these lines into a Flask view, and visit it with your browser:

import pdb

The page won't load, but you can switch back to the Flask server running in your terminal, where you'll see this:

This is the Python debugger, a GDB-like debugger that lets you run arbitrary Python code with access to the request object, the database, and everything else your application provides.

You can use dir() to inspect objects and see their properties and methods. The standard GDB commands also work, like 'n' to step to the next line, or 'c' to continue and execute the rest of the code in the controller.

You can even write code in PDB, executing it to see if it works as expected, and then copying it into your application. Put it above the PDB import, and then refresh the page and continue coding. It's a great way to debug controller code or to learn a new Python library, experimenting with PDB and a text editor side-by-side.