Debugging with PDB

Even with a comprehensive automated test suite, we can still get into situations where we need a debugger to figure out what's going on. Fortunately, Python includes a powerful debugger with the standard library: PDB. PDB is a command-line debugger, and if you're familiar with tools like GDB then you'll already have a good idea of how to use PDB.

The key advantage of PDB over other Python debuggers is that, being part of Python itself, PDB is available pretty much anywhere that Python is, including specialized environments where the Python language has been embedded into larger systems, such as ESRI's ArcGIS Geographical Information System. That said, it can be much more comfortable to use a

so-called graphical debugger, such as the ones included with products such as Jetbrains'  PyCharm or Microsoft's Python Tools for Visual Studio. You should feel free to skip this chapter until such time that familiarity with PDB becomes more pressing; you won't be missing anything we rely on later in this book or in The Python Journeyman or The Python Master.

PDB is different from many debugging tools in that it's not really a separate program but rather a module just like any other Python module. You can import pdb into any program and start the debugger using the set_trace() function call. This function simply starts the debugger at whatever point you are at in the program's execution.

For our first look at PDB, let's use a REPL and start the debugger with set_trace():

>>> import pdb
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb)

You'll see that after you execute set_trace() your prompt changes from the triple-chevron to (Pdb) – this is how you know you're in the debugger.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset