Mike Driscoll Profile picture
I tweet about everything #Python Writing about Python @mousevspython @realpython Teaching at @TeachMePy Author of multiple books - https://t.co/MdP25zw5zQ

Nov 18, 2021, 17 tweets

Python comes with its own built-in debugger called `pdb`.

Let's talk about that in a mini-thread!

๐Ÿงต๐Ÿ๐Ÿ‘‡

`pdb` stands for Python debugger. It is a built-in part of Python's standard library

Here is a link to the documentation:

docs.python.org/3/library/pdb.โ€ฆ

To start debugging code with `pdb`, you need to write some code.

Here's the code you'll be using:

There are several different ways to debug code with `pdb`. Open up the Python REPL / interpreter in the same folder as the code you wish to debug.

Then run the following to run your code in the Python debugger

`pdb` uses many of the same commands as `gdb`, the C++ debugger. If you are familiar with `gdb`, then using `pdb` will be a snap!

In this code, you call `run()` to run your code. Then you type `continue` to continue the run. You can also type `c` as a shortcut for `continue`

When debugging, your code will run until one of the following occurs:

๐Ÿ An exception is raised
๐Ÿ You hit a breakpoint
๐Ÿ The code finishes successfully

You can also run the Python debugger on the command line by using a command like this one:

The output of running the code on the command line is different than running it in the REPL

The prompt, (Pdb) will appear. You will need to issue a command to `continue` or to step through your code

Here is an example console session where you use the `step` or `s` command to step through the code with `pdb`

You can add a breakpoint inside the `pdb` session itself by typing `break` followed by the line number you wish to add the breakpoint to

You can also add a breakpoint directly to your #Python code using `pdb.set_trace()`

Here is an example:

Starting in #Python 3.7, you can use the `breakpoint` keyword instead of `pdb.set_trace()`

If you run this code in PyCharm, VS Code and other popular debuggers, the IDE's debugger will launch instead of `pdb` when it reaches the `breakpoint()`

You can read more about the `breakpoint` keyword in PEP 553

python.org/dev/peps/pep-0โ€ฆ

If you can't remember a `pdb` command, just type `help` to get a full listing

This series of tweets is based on my tutorial @mousevspython

blog.pythonlibrary.org/2020/07/07/pytโ€ฆ

The full code examples can also be found on my PyTips repo:

github.com/driscollis/pytโ€ฆ

Thanks for reading my thread on Python's debugger, `pdb`!

Follow me to learn more Python!

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling