How to Debug Python Code in Visual Studio Code

Visual Studio Code (VS Code) is a popular editor that offers powerful debugging features for Python. Whether you’re stepping through code, inspecting variables, or diagnosing tricky bugs, VS Code provides all the tools you need for efficient debugging. This tutorial will guide you through setting up and using VS Code’s debugger for Python projects.

Setting Up Python Debugging in VS Code

Step 1: Install VS Code and Python Extension

  1. Download and install Visual Studio Code.
  2. Install the Python extension by Microsoft:
    • Open the Extensions view (Ctrl+Shift+X or Cmd+Shift+X on macOS).
    • Search for “Python” and click Install.

Step 2: Configure Your Python Environment

  1. Install Python if you haven’t already:
    sudo apt install python3  # Linux
    brew install python3      # macOS
    winget install Python.Python.3 # Windows
    
  2. Set your interpreter in VS Code:
    • Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P).
    • Type Python: Select Interpreter and choose the appropriate environment.

Step 3: Create a Debug Configuration

A debug configuration tells VS Code how to run your program during debugging. It defines:

To create a debug configuration:

  1. Open your Python project in VS Code.
  2. Click on the Run and Debug icon (Ctrl+Shift+D or Cmd+Shift+D) in the Activity Bar.
  3. Click Create a launch.json file and select Python.

The default configuration for debugging the currently open file will look like this:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Current File",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal"
    }
  ]
}

This setup allows you to debug your Python file directly. You can modify this file later to handle more complex scenarios, such as debugging Django or Flask applications.

Setting Breakpoints

Breakpoints let you pause program execution at specific lines to inspect variables and the flow of your code.

Adding a Breakpoint

  1. Open a Python file in VS Code.
  2. Click to the left of a line number, or press F9, to set a breakpoint.
  3. A red dot will appear, indicating the breakpoint is active.

Conditional Breakpoints

To pause execution only under specific conditions:

  1. Right-click the red dot.
  2. Select Edit Breakpoint Condition.
  3. Enter a condition like x > 10.

Example Code for Debugging

def calculate_area(length, width):  
    area = length * width  
    print(f"The area is {area}")  
    return area

length = 5  
width = 10  
result = calculate_area(length, width)

Add a breakpoint on the area = length * width line to pause execution and inspect variables.

Running the Debugger

  1. Open the Run and Debug view (Ctrl+Shift+D or Cmd+Shift+D).
  2. Select Python: Current File in the dropdown menu.
  3. Click the green play button or press F5 to start debugging.

Debugging Controls

Inspecting Variables and Expressions

Variables Panel

The Variables panel in the Debug Sidebar displays:

Watch Expressions

  1. In the Debug Sidebar, click + Add Expression under WATCH.
  2. Enter a variable or expression (e.g., length * width).
  3. The debugger updates the value dynamically as you step through the code.

Debug Console

Use the Debug Console to evaluate expressions interactively:

  1. Type area in the console and press Enter to see its current value.
  2. You can also execute Python code, like length + width, to test assumptions.

Advanced Debugging Features

Logging Breakpoints

Instead of pausing execution, logging breakpoints print a message to the console.

  1. Right-click a breakpoint.
  2. Select Edit Logpoint.
  3. Enter a message like "Area: {area}".

Debugging Multiple Files

If your project has multiple files, you can debug across them by setting breakpoints in different modules.

Remote Debugging

VS Code supports debugging remote Python scripts running on a server or container. Add a remote interpreter to your launch.json file for remote configurations.

Debugging Django or Flask Applications

VS Code includes built-in configurations for debugging popular frameworks:

Tips for Efficient Debugging

  1. Use Debug Profiles: Create multiple configurations in launch.json for different scenarios.
  2. Keep an Eye on Logs: Combine debugging with logging for greater insights.
  3. Leverage Extensions: Use VS Code extensions like Python Test Explorer for debugging tests.
  4. Automate Testing: Integrate debugging with Pytest to debug failing test cases directly.

Conclusion

Visual Studio Code simplifies Python debugging with its intuitive interface and robust features. From breakpoints and variable inspection to remote debugging and framework-specific setups, VS Code offers a complete toolkit for diagnosing and fixing bugs efficiently.

Start using VS Code for debugging today and streamline your development workflow!