This document covers additional debugging techniques including IDE breakpoints, Visual Studio Code debugger features, conditional breakpoints variable inspection, and comparing IDE debugging with command-line approaches. IDE-based debugging strategies.
This document explores additional debugging techniques beyond command-line tools, focusing on IDE-based debugging with Visual Studio Code, including breakpoint usage, conditional breakpoints, variable inspection, step-through execution, and comparing advantages and disadvantages of IDE debugging versus command-line approaches.
While command-line debugging tools like PDB provide powerful capabilities, Integrated Development Environments (IDEs) offer visual debugging interfaces that can make the debugging process more intuitive and efficient. Understanding these tools and techniques expands the debugging toolkit available for diagnosing and fixing issues.
A breakpoint is a debugging technique accomplished by setting a stopping point on a specific line of code or condition. When code runs in a debugger, execution pauses at that point, allowing inspection of program state.
| Step | Action |
|---|---|
| 1 | Developer sets breakpoint on code line |
| 2 | Code runs in debugger |
| 3 | Execution pauses when breakpoint is reached |
| 4 | Developer inspects variables and state |
| 5 | Developer steps through code or continues execution |
| 6 | Execution resumes or restarts |
When execution pauses at a breakpoint:
Visual Studio Code (VS Code or VSCode) is a free, open-source integrated development environment (IDE) from Microsoft that allows writing, running, debugging, and testing code in a single window.
| Feature | Description |
|---|---|
| Free and open-source | No licensing costs |
| Cross-platform | Works on Windows, macOS, Linux |
| Multi-language support | Supports almost any programming language |
| Extensive extensions | Thousands of plugins and extensions available |
| Integrated debugger | Built-in debugging capabilities |
| Git integration | Source control built-in |
| Customizable | Highly configurable interface and shortcuts |
VS Code requires the Python extension for debugging Python code:
Ctrl+Shift+X)Create a .vscode/launch.json file in the project directory:
1{
2 "version": "0.2.0",
3 "configurations": [
4 {
5 "name": "Python: Current File",
6 "type": "python",
7 "request": "launch",
8 "program": "${file}",
9 "console": "integratedTerminal",
10 "justMyCode": true
11 }
12 ]
13}
| Option | Description | Example |
|---|---|---|
name | Configuration name | “Python: Current File” |
type | Debugger type | “python” |
request | Launch or attach | “launch” |
program | Script to debug | “${file}” or “app.py” |
args | Command-line arguments | ["--verbose", "input.txt"] |
cwd | Working directory | “${workspaceFolder}” |
env | Environment variables | {"DEBUG": "true"} |
justMyCode | Debug only user code | true or false |
Multiple ways to set breakpoints:
F9 on desired line 1def calculate_total(items):
2 total = 0 # Click here to set breakpoint
3 for item in items:
4 total += item['price']
5 return total
6
7result = calculate_total([
8 {'name': 'Widget', 'price': 10},
9 {'name': 'Gadget', 'price': 20}
10])
11print(result)
F5 or click “Run and Debug” icon| Icon | Meaning |
|---|---|
| Red circle | Active breakpoint |
| Gray circle | Disabled breakpoint |
| Red circle with check | Breakpoint hit |
| Hollow circle | Unverified breakpoint |
Conditional breakpoints only pause execution when a specified expression evaluates to true. This is particularly useful for debugging loops where stopping at every iteration would be impractical.
1def process_items(items):
2 results = []
3 for i, item in enumerate(items):
4 # Set conditional breakpoint: i == 5
5 processed = transform_item(item)
6 results.append(processed)
7 return results
8
9# Only stops when i equals 5
10items = list(range(10))
11process_items(items)
| Type | Description | Example |
|---|---|---|
| Expression | Stops when expression is true | x > 100 |
| Hit Count | Stops after N hits | == 5 (stops on 5th hit) |
| Log Message | Logs message without stopping | Item {i} processed |
1def analyze_data(records):
2 for record in records:
3 # Conditional breakpoint: record['status'] == 'error' and record['priority'] > 5
4 result = process_record(record)
5 save_result(result)
Breakpoint only triggers when both conditions are true.
| Button | Shortcut | Action |
|---|---|---|
| Continue | F5 | Resume execution |
| Step Over | F10 | Execute next line |
| Step Into | F11 | Enter function calls |
| Step Out | Shift+F11 | Exit current function |
| Restart | Ctrl+Shift+F5 | Restart debugging |
| Stop | Shift+F5 | Stop debugging |
Shows all variables in current scope:
Variables can be:
Monitor specific expressions:
Examples:
len(items)total / countuser.is_active and user.has_permission('admin')Shows function call hierarchy:
Manage all breakpoints:
| Scenario | Why VS Code Breakpoints Work Well |
|---|---|
| Runtime errors | Visual inspection of state at crash point |
| Loop debugging | Conditional breakpoints avoid stopping every iteration |
| Complex logic | Step through conditionals and see exact path taken |
| Variable inspection | Watch panel shows real-time value changes |
| General testing | Quick setup for exploratory debugging |
| Multi-file debugging | Navigate between files while debugging |
1def calculate_average(numbers):
2 # Set breakpoint here
3 total = sum(numbers)
4 count = len(numbers)
5 # Set breakpoint here to inspect before division
6 average = total / count # ZeroDivisionError if empty list
7 return average
8
9# Test with problematic input
10result = calculate_average([]) # Causes error
Breakpoints reveal:
numbers is empty listtotal is 0count is 0 1def process_order(order):
2 # Set breakpoint
3 if order['status'] == 'pending':
4 if order['payment_method'] == 'credit_card':
5 if order['total'] > 1000:
6 # Set conditional breakpoint: order['total'] > 5000
7 apply_special_processing(order)
8 else:
9 apply_standard_processing(order)
10 elif order['payment_method'] == 'paypal':
11 apply_paypal_processing(order)
12 elif order['status'] == 'completed':
13 send_confirmation(order)
Step through to see exactly which path executes.
| Advantage | Description |
|---|---|
| Visual inspection | See code and variables simultaneously |
| No code modification | No need to add print statements |
| Step-through execution | Execute one line at a time |
| Real-time variable watching | Monitor expressions as code runs |
| Easy navigation | Click to jump between frames and files |
| Conditional control | Stop only when specific conditions met |
| Rich variable display | Expand complex objects and data structures |
| Stack navigation | Move through call hierarchy easily |
1def calculate_compound_interest(principal, rate, years):
2 # Watch these expressions:
3 # - principal
4 # - rate
5 # - years
6 # - amount (after calculation)
7
8 amount = principal
9 for year in range(years):
10 # Set breakpoint inside loop
11 amount = amount * (1 + rate)
12 # Watch panel shows amount updating each iteration
13
14 return amount
15
16result = calculate_compound_interest(1000, 0.05, 10)
Watch panel shows amount growing each iteration without adding print statements.
| Disadvantage | Description | Impact |
|---|---|---|
| Performance overhead | Debugger slows execution | Significant for large datasets |
| Setup time | Configuration required | 5-10 minutes per project |
| Resource intensive | Uses more memory and CPU | May affect other applications |
| Not for production | Cannot debug deployed code | Requires alternative logging |
| Learning curve | Interface must be learned | Initial productivity loss |
1import time
2
3def process_large_dataset(data):
4 results = []
5 for item in data:
6 result = item * 2
7 results.append(result)
8 return results
9
10data = list(range(1000000))
11
12# Command line execution: ~0.1 seconds
13# VS Code debugger: ~5-10 seconds (50-100x slower)
Initial project setup:
launch.json configurationTotal time: 5-15 minutes depending on complexity.
| Feature | Print Statements | PDB | VS Code |
|---|---|---|---|
| Setup time | None | None | 5-10 minutes |
| Visual interface | No | No | Yes |
| Variable inspection | Manual | Interactive | Visual |
| Performance impact | Minimal | Moderate | High |
| Learning curve | None | Moderate | Moderate |
| Production use | Yes (logging) | Limited | No |
| Conditional breaks | No | Yes | Yes |
| Step execution | No | Yes | Yes |
| Remote debugging | No | Limited | Yes |
| Scenario | Recommended Tool | Reason |
|---|---|---|
| Quick value check | Print statements | Fastest |
| Production debugging | Logging module | Safe for production |
| Complex algorithm | VS Code | Visual step-through |
| Remote server | PDB or logging | No GUI available |
| Performance-critical | Logging | Minimal overhead |
| Learning codebase | VS Code | Easy navigation |
| Intermittent bugs | Logging | Persistent records |
1# Quick debugging: print statements
2def quick_debug():
3 x = 10
4 print(f"DEBUG: x = {x}")
5 return x
6
7# Development debugging: VS Code breakpoints
8def dev_debug():
9 x = 10 # Set breakpoint here
10 return x
11
12# Production debugging: logging
13import logging
14
15def prod_debug():
16 x = 10
17 logging.debug(f"x = {x}")
18 return x
Note
VS Code setup usually takes a few minutes initially, but the time investment pays off for complex debugging sessions. For simple issues, command-line tools like PDB or print statements may be faster.
Log messages without stopping execution:
Item {i} has value {item}Break on exceptions:
Debug code running on remote servers:
1{
2 "name": "Python: Attach to Remote",
3 "type": "python",
4 "request": "attach",
5 "connect": {
6 "host": "remote.server.com",
7 "port": 5678
8 },
9 "pathMappings": [
10 {
11 "localRoot": "${workspaceFolder}",
12 "remoteRoot": "/app"
13 }
14 ]
15}
Breakpoints provide powerful debugging capabilities by pausing code execution at specific points. VS Code offers visual debugging interface with features like conditional breakpoints, variable inspection, and step-through execution. While VS Code debugging is slower than command-line execution and requires initial setup, it provides significant advantages for complex debugging scenarios. Choosing the right debugging tool depends on the context: print statements for quick checks, logging for production, PDB for remote servers, and VS Code for development.
IDE-based debugging with tools like VS Code provides visual, interactive debugging capabilities that complement command-line tools like PDB. Understanding when to use breakpoints, conditional breakpoints, and visual inspection versus command-line debugging enables developers to choose the most effective approach for each situation. While VS Code requires initial setup and runs slower than command-line execution, its visual interface and rich features make it invaluable for complex debugging scenarios in development environments.