Open In App

How to debug a python module in VSCode

Last Updated : 02 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Debugging is an essential part of the development process, allowing developers to inspect their code, understand its behavior, and identify and fix issues. Visual Studio Code (VSCode) is a powerful, free code editor that offers robust debugging capabilities for Python. This article will guide you through the process of setting up and using VSCode to debug a Python module, from initial setup to advanced debugging techniques.

What is Debugging in Python?

Debugging is a process in which we identify, analyze, and fix bugs and errors in a Python program. It is a critical process to ensure the proper functioning of the software. To achieve such results we utilize some techniques and tools such as :

  • Simple Print() Statements: this is the technique we use when we start learning to code, in this we just add print() statements for the values and expression whose execution flow we want to track.
  • Error Messages and Stack Traces: when we execute a Python code with errors the interpreter provides us with an error message with the error type & location, which provides us with the information to debug the code.
  • Logging for more detailed Output: Using "logging" modules we can get more control and flexibility to record varying severity of bugs compared to print() statements.
  • Interactive Debugging with "pdb": with the help of Python Debugger("pdb") we can set up breakpoints throughout the code and examine the code stepwise inspecting variables interactively.
  • Writing and Running Automated Tests: Creating automated tests using tools like "unittest" or "pytest" to automatically verify the functionality of the code.
  • Using Static Code Analysis Tool: We can use tools like "pylint", "flaske8" or"mypy" to analyze the code and find potential errors.
  • Profiling for Performance Issues: we can use profiling tools like "cProfile" to identify and analyze performance bottlenecks in the code.
  • Exception Handling: Implementing "try" and "catch" blocks to manage runtime errors and respond to them gracefully.
  • Advanced Tools Provided by IDE: We can utilize integrated debugging features in IDE like breakpoints, variable watching, and call stack inspection.

Setting Up VSCode for Python

Before you can start debugging, you need to ensure that VSCode is properly configured for Python development. This involves installing the necessary extensions and selecting the appropriate Python interpreter.

Configuring the Python Interpreter

Open the command palette in VS Code (can be accessed by pressing 'ctrl + shift + p' [windows] or 'cmd + Shift + p' [ Mac]) and type " Python: Select Interpreter". Choose the interpreter for python for your virtual environment.

Configuring Python Interpreter
Configuring Python Interpreter
Selecting Python Interpreter
Selecting Python Interpreter

Make sure VS Code can access the Python interpreter without any issues to check just run a basic Python code such as to print hello world to screen.

Set Up the Python Environment

Open Terminal in VS Code and navigate to your project directory. Create a virtual environment in the project directory by running the following command. This will create a virtual environment with the name 'myvenv'.

python -m venv myenv

Now, you can activate the virtual environment using the following command

On Windows:

myenv\Scripts\activate

On MacOS

source myenv/bin/activate

Python Debug Configuration

To debug your Python code, you need to set up a debug configuration. This configuration tells VSCode how to run and debug your code.

Create a Debug Configuration

First, open the Debug view by clicking on the debug icon in the activity bar. Then click on the gear icon to open the 'launch.json' file. If it doesnt exist, VS Code will prompt you to create one. Choose "Python" from the list of options.

Below is a example for the basic configuration file for debugging.

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

Set Breakpoints

Breakpoints allow you to pause the execution of your code at specific lines, so you can inspect the program state. We can set breakpoints by opening the file that we want to debug. Then, click on the ribbon left of the line numbers, a red dot would appear indicating the Breakpoint.

setting-breakpoints
Adding Breakpoints

Once the breakpoints are set, you can see the list of all set breakpoints in 'breakpoints' section under Debug view.

Breakpoints in debug view
Breakpoints in debug view

We can also edit a breakpoint to add condition to it, such as stopping only when a variable reaches a certain value. This can be done by right clicking the breakpoint added earlier.

Running and Debugging Python Module

With breakpoints set, you can start the debugging process and step through your code to identify issues.

Start Debugging:

In the Debug view make sure your configuration (e.g.:"Python: Current File") is selected. Click the Green play button (Start Debugging) or press 'F5'. Once you start debugging process, you can see a small clock icon appearing in the debug view.

Debugging started
Debugging started

Using Debugging Tools

We can use the toolbar to control execution:

  • Continue (F5): Runs the program until the next breakpoint.
  • Step Over (F10): Executes the next line of code but does not step into functions.
  • Step Into (F11): Steps into functions to allow you to debug inside them.
  • Step Out (Shift+F11): Steps out of the current function.
  • Restart (Ctrl+Shift+F5): Restarts the debugging session.
  • Stop (Shift+F5): Stops the debugging session.
  • Variables Pane: Inspect variables and their values.
  • Watch Pane: Add expressions to watch their values as you step through the code.
  • Call Stack Pane: See the call stack of the program.
  • Breakpoints Pane: Manage your breakpoints.
  • Debug Console: Execute Python commands in the context of the program being debugged.

Inspecting Variables and Expressions

VSCode provides tools to inspect the state of your variables and evaluate expressions while debugging.

Variable Pane

This area, view and inspect the values of the local and the global variables. It shows the variable with their current values at the point of execution. While debug mode, hover your mouse pointer over the variables in the code to assess their current state in a tooltip.

Watch Pane

In the debug view, under the watch section u can add variable and expression to monitor their values throughout the execution. Click '+' to add the variable or expression.

Call Stack Pane

You can view the current call stack to understand the sequence of the function calls leading to the current state of execution.

The Debugging Console

This console allows us to execute Python commands to debug the required python code. You can use it to evaluate expressions, modify variables and call functions.

  • Open Debug Console: To open debug console click on the debug console tab in the lower part of the VS Code window.
  • Evaluate Expressions: You are directly type and execute python expressions on the debug console.

Advanced Debugging Techniques

VSCode offers advanced debugging features, such as exception breakpoints, logpoints, multi-threaded debugging, and remote debugging.

Conditional Breakpoints

To edit a breakpoint just right click on the breakpoint and select edit breakpoint. You can then add conditions like "x==5" which only breaks when the condition is true.

Exception Breakpoints

Set breakpoints on exceptions to pause execution when specific exceptions are thrown. Click the gear icon in the Breakpoints pane and select "Add Exception Breakpoint.

Function Breakpoint

In the break panel, click the '+' sign to add a function to a breakpoint by entering its name which breaks when the function is called.

Logpoints

They are similar to breakpoints but instead of breaking they log a message to the console. to add them right click on the ribbon left of the line number and select "add Logpoint".

Remote Debugging

Configure launch.json for remote debugging to connect to a remote Python interpreter, useful for debugging code running on another machine or in a container.

Conclusion

Debugging Python code in VSCode is a powerful way to understand and fix issues in your code. By following the steps you can effectively setup and start you debugging journey in Python.


Next Article
Article Tags :
Practice Tags :

Similar Reads