Chapter 10. Debugging and Testing

All of the projects from the previous chapters — whether it was a project that accessed files on the file system, interacted with a database, or served pages on a web server — have one thing in common: They didn't work the first time.

It is inevitable as a programmer that you will run into errors in your programs. Fortunately, Python has built-in features to help you discover those "bugs" and take care of them:

  • The Python debugger (which is actually just another Python module itself) supports setting decision markers called breakpoints and allows you to "step" through code one line at a time. It supports very sophisticated debugging if needed, including providing a stack viewer.

  • There are several Python automated test frameworks that enable you to build automated tests to test your code. Having automated tests enables you to add functionality and run your tests to verify that you haven't broken anything.

The Python Debugger

The basic purpose of a debugger is to enable a developer to "walk" through a program as it executes, noticing specific areas where the program breaks, and where it could be modified or optimized to work better.

Running the Debugger

The Python debugger can be utilized in several different ways:

Importing the pdb Module Directly

The pdb module is the Python debugger. You can access it by importing it directly either in a script or in the Python console:

Import pdb

With the debugger module imported, you then have access to many different functions ...

Get Python® Create-Modify-Reuse now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.