Other Debugging Techniques

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.


Introduction

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.


Understanding Breakpoints

What Are Breakpoints

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.

How Breakpoints Work

StepAction
1Developer sets breakpoint on code line
2Code runs in debugger
3Execution pauses when breakpoint is reached
4Developer inspects variables and state
5Developer steps through code or continues execution
6Execution resumes or restarts

Breakpoint Capabilities

When execution pauses at a breakpoint:

  • Inspect variable values
  • Step through code one line at a time
  • Evaluate expressions
  • Modify variable values
  • View call stack
  • Resume or restart execution

Visual Studio Code for Debugging

What Is VS Code

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.

Key Features

FeatureDescription
Free and open-sourceNo licensing costs
Cross-platformWorks on Windows, macOS, Linux
Multi-language supportSupports almost any programming language
Extensive extensionsThousands of plugins and extensions available
Integrated debuggerBuilt-in debugging capabilities
Git integrationSource control built-in
CustomizableHighly configurable interface and shortcuts

Setting Up VS Code for Python Debugging

Installing Python Extension

VS Code requires the Python extension for debugging Python code:

  1. Open VS Code
  2. Click Extensions icon (or press Ctrl+Shift+X)
  3. Search for “Python”
  4. Install the official Python extension by Microsoft

Creating Debug Configuration

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}

Configuration Options

OptionDescriptionExample
nameConfiguration name“Python: Current File”
typeDebugger type“python”
requestLaunch or attach“launch”
programScript to debug“${file}” or “app.py”
argsCommand-line arguments["--verbose", "input.txt"]
cwdWorking directory“${workspaceFolder}”
envEnvironment variables{"DEBUG": "true"}
justMyCodeDebug only user codetrue or false

Using Breakpoints in VS Code

Setting Breakpoints

Multiple ways to set breakpoints:

  1. Click in the gutter (left of line numbers)
  2. Press F9 on desired line
  3. Right-click line and select “Add Breakpoint”
 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)

Starting Debug Session

  1. Set breakpoints in code
  2. Press F5 or click “Run and Debug” icon
  3. Select “Python: Current File” configuration
  4. Execution pauses at first breakpoint

Breakpoint Indicators

IconMeaning
Red circleActive breakpoint
Gray circleDisabled breakpoint
Red circle with checkBreakpoint hit
Hollow circleUnverified breakpoint

Conditional Breakpoints

What Are Conditional Breakpoints

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.

Setting Conditional Breakpoints

  1. Right-click in gutter
  2. Select “Add Conditional Breakpoint”
  3. Choose “Expression” or “Hit Count”
  4. Enter condition

Example: Loop Debugging

 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)

Conditional Breakpoint Types

TypeDescriptionExample
ExpressionStops when expression is truex > 100
Hit CountStops after N hits== 5 (stops on 5th hit)
Log MessageLogs message without stoppingItem {i} processed

Advanced Conditions

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.


VS Code Debug Interface

Debug Toolbar

ButtonShortcutAction
ContinueF5Resume execution
Step OverF10Execute next line
Step IntoF11Enter function calls
Step OutShift+F11Exit current function
RestartCtrl+Shift+F5Restart debugging
StopShift+F5Stop debugging

Variables Panel

Shows all variables in current scope:

  • Local variables
  • Global variables
  • Function parameters
  • Object properties

Variables can be:

  • Expanded to view nested properties
  • Modified by right-clicking and selecting “Set Value”
  • Watched by adding to Watch panel

Watch Panel

Monitor specific expressions:

  1. Click “Add Expression” in Watch panel
  2. Enter expression to watch
  3. Value updates as code executes

Examples:

  • len(items)
  • total / count
  • user.is_active and user.has_permission('admin')

Call Stack Panel

Shows function call hierarchy:

  • Current function at top
  • Calling functions below
  • Click any frame to view its context

Breakpoints Panel

Manage all breakpoints:

  • Enable/disable individual breakpoints
  • Enable/disable all breakpoints
  • Delete breakpoints
  • View breakpoint conditions

When to Use Breakpoints with VS Code

Ideal Scenarios

ScenarioWhy VS Code Breakpoints Work Well
Runtime errorsVisual inspection of state at crash point
Loop debuggingConditional breakpoints avoid stopping every iteration
Complex logicStep through conditionals and see exact path taken
Variable inspectionWatch panel shows real-time value changes
General testingQuick setup for exploratory debugging
Multi-file debuggingNavigate between files while debugging

Example: Runtime Error 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 list
  • total is 0
  • count is 0
  • Division by zero about to occur

Example: Complex Logic Debugging

 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.


Advantages of VS Code Breakpoints

Benefits

AdvantageDescription
Visual inspectionSee code and variables simultaneously
No code modificationNo need to add print statements
Step-through executionExecute one line at a time
Real-time variable watchingMonitor expressions as code runs
Easy navigationClick to jump between frames and files
Conditional controlStop only when specific conditions met
Rich variable displayExpand complex objects and data structures
Stack navigationMove through call hierarchy easily

Example: Variable Watching

 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.


Disadvantages of VS Code Breakpoints

Limitations

DisadvantageDescriptionImpact
Performance overheadDebugger slows executionSignificant for large datasets
Setup timeConfiguration required5-10 minutes per project
Resource intensiveUses more memory and CPUMay affect other applications
Not for productionCannot debug deployed codeRequires alternative logging
Learning curveInterface must be learnedInitial productivity loss

Performance Comparison

 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)

Setup Requirements

Initial project setup:

  1. Install VS Code
  2. Install Python extension
  3. Create launch.json configuration
  4. Configure Python interpreter
  5. Set up virtual environment (if needed)
  6. Install project dependencies

Total time: 5-15 minutes depending on complexity.


Comparing Debugging Approaches

Tool Comparison

FeaturePrint StatementsPDBVS Code
Setup timeNoneNone5-10 minutes
Visual interfaceNoNoYes
Variable inspectionManualInteractiveVisual
Performance impactMinimalModerateHigh
Learning curveNoneModerateModerate
Production useYes (logging)LimitedNo
Conditional breaksNoYesYes
Step executionNoYesYes
Remote debuggingNoLimitedYes

When to Use Each Approach

ScenarioRecommended ToolReason
Quick value checkPrint statementsFastest
Production debuggingLogging moduleSafe for production
Complex algorithmVS CodeVisual step-through
Remote serverPDB or loggingNo GUI available
Performance-criticalLoggingMinimal overhead
Learning codebaseVS CodeEasy navigation
Intermittent bugsLoggingPersistent records

Best Practices

Using Breakpoints Effectively

  • Set breakpoints near suspected problem areas, not at beginning
  • Use conditional breakpoints for loops and repeated code
  • Remove breakpoints before committing code
  • Use logging for long-running processes
  • Combine techniques: logging for production, breakpoints for development

VS Code Tips

  • Use keyboard shortcuts for faster debugging
  • Configure launch.json for common scenarios
  • Save workspace settings for team consistency
  • Use logpoints instead of print statements
  • Enable “Just My Code” to skip library code

Choosing the Right Tool

 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

Advanced VS Code Features

Logpoints

Log messages without stopping execution:

  1. Right-click in gutter
  2. Select “Add Logpoint”
  3. Enter message template: Item {i} has value {item}
  4. Messages appear in Debug Console

Exception Breakpoints

Break on exceptions:

  1. Open Breakpoints panel
  2. Check “Uncaught Exceptions”
  3. Check “Caught Exceptions” (optional)
  4. Debugger stops when exception occurs

Remote Debugging

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}

Key Takeaways

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.


Conclusion

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.


FAQ