Debugging in VS Code with Jupyter Notebooks involves more than just stepping through your code—it also includes inspecting variables, checking execution flow, and diagnosing issues in the Jupyter environment itself. Here’s a comprehensive guide:
1. Debugging Your Code in Jupyter Notebooks
Basic Debugging Steps
Set Breakpoints:
Click the left gutter (next to line numbers) to add a red breakpoint.
Right-click a breakpoint to add conditions (e.g., hit when a variable equals a value).
Start Debugging:
Press F5 or click the "Run and Debug" button (play icon with a bug).
Select "Jupyter: Current File" if prompted.
Debugging Tools:
Step Over (F10): Execute the current line and move to the next.
Step Into (F11): Dive into a function call.
Step Out (Shift+F11): Exit the current function.
Continue (F5): Resume execution until the next breakpoint.
Restart/Stop: Use the toolbar buttons to restart or stop debugging.
Inspect Variables:
Hover over variables to see their values.
Use the Debug Console to evaluate expressions.
Check the Variables panel in the debug sidebar.
Call Stack:
View the call stack in the debug panel to trace function calls.
2. Debugging Jupyter-Specific Issues
Common Problems & Fixes
Kernel Not Responding:
Restart the kernel (Ctrl+Shift+P > "Jupyter: Restart Kernel").
Check for infinite loops or memory leaks in your code.
Cell Execution Errors:
Use %debug magic command after an error to enter post-mortem debugging.
Example:
try:
# Your code
except:
%debug
Variable Inspection:
Use print() or display() to log variables.
Use %%timeit to profile slow cells.
Kernel Logs:
Open the Output panel (Ctrl+Shift+U) and select "Jupyter" to see kernel logs.
Environment Issues:
Ensure the correct Python interpreter is selected (Ctrl+Shift+P > "Python: Select Interpreter").
Check for missing packages (pip install -r requirements.txt).
3. Advanced Debugging Techniques
Using pdb (Python Debugger)
Insert import pdb; pdb.set_trace() in your code to pause execution and inspect variables.
Example:
def my_function():
x = 10
import pdb; pdb.set_trace() # Execution pauses here
return x
Logging
Use Python’s logging module to track execution:
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message")