Debugging in Python
What is Debugging in Python?
Debugging in Python is the process of finding and fixing logic, syntax, or runtime errors in your code. Python offers multiple ways to debug — from simple print() statements to powerful IDE debuggers and command-line tools.
Top Debugging Techniques in Python
1. Use print() Statements
Old but gold. Print variable values to trace logic errors.
def calculate_area(length, width):
print("Length:", length)
print("Width:", width)
return length * width
print("Area:", calculate_area(5, 0))
2. Use the Built-in pdb Debugger
Python's built-in PDB module allows you to step through code, inspect variables, and evaluate expressions.
import pdb
def divide(x, y):
pdb.set_trace()
return x / y
divide(10, 2)
Use commands like:
- n (next)
- c (continue)
- q (quit)
- p var_name (print variable)
3. Use IDE Debuggers (like PyCharm, VS Code)
Modern IDEs have built-in debuggers:
- Set breakpoints with a click
- Watch variables live
- Step into functions
- View the call stack
4. Use assert for Quick Checks
def is_positive(n):
assert n > 0, "Number must be positive"
return True
is_positive(-5)
Output:
AssertionError: Number must be positive
5. Logging Instead of Printing
Use the logging module for real-world debugging (especially in production).
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message.")
6. Unit Testing to Catch Bugs Early
Use Python's built-in unittest module to test individual units of your code.
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
unittest.main()
7. Watch for Common Bugs
- Uninitialized variables
- Off-by-one errors in loops
- Wrong indentation
- Mutable default arguments (e.g., def f(x=[]))
- Import errors due to incorrect file/module paths
Advanced Debugging Tools
Tool | Description |
---|---|
pdb | Built-in Python debugger |
ipdb | IPython-enhanced pdb |
pudb | Full-screen, terminal-based visual debugger |
PyCharm Debugger | GUI debugger with breakpoints, watch, and step |
VS Code Debugger | Lightweight and powerful IDE debugger |
Best Practices for Debugging Python Code
- Keep code modular and readable
- Write unit tests before debugging
- Comment complex logic
- Use version control (Git) to isolate bugs
- Avoid long functions (split logic into smaller units)