Debugging in Python, part 2: Developing a debugging mindset
MP 139: A systematic, inquisitive approach makes debugging simple issues easier, and complex bugs possible.
Note: This post is part of an ongoing series about debugging in Python. The posts in this series will only be available to paid subscribers for the first 6 weeks. After that they will be available to everyone. Thank you to everyone who supports my ongoing work on Mostly Python.
One of the most important things you can do to become effective at debugging is to adopt a consistent, systematic approach to every bug you deal with. This mindset will help you debug simple issues quickly, and make it possible to resolve complex issues as efficiently as you can.
Overview
Before getting into the details, let's take a step back and look at the big picture. Much of debugging boils down to these three things:
- How can I recreate the bug?
- What's the root cause of the bug? What's the best way to address the root issue?
- Once it's fixed, how can I make sure this bug won't appear again?
This leaves out a lot of specifics, especially when it comes to handling complex bugs. But these three bullet points outline a clear and consistent mindset when approaching bugs of any size and significance.
Recreating bugs
In order to work on a bug, you need to be able to trigger that bug repeatedly. In order to know that you've fixed the bug, you have to be able to run the project in the same way that produced the bug as well.
If you're working on a single .py file that can only be run one way, you'll probably see the same bug every time you run the program. But most projects can be run in a variety of ways, with a variety of different inputs, and the user can often request different kinds of output. Unless you've run into a serious bug that affects all use cases, you'll probably have to run the project in a very specific way in order to recreate the bug. That's why it's so important to capture as much information as you can when a bug first appears. Some of the information you capture may end up being irrelevant, but you can't always know that ahead of time.
There are a number of specific questions to consider asking in order to help recreate a bug:
This post is only available to paid subscribers at the moment. It will be available to everyone 6 weeks after posting. If you'd like to continue reading now, please support my work by signing up for a paid subscription.