Visual Studio Code for Python Development (2023)

Introduction

  • Introduction
  • Installing the Python Extension
  • Virtual Environments
  • Editing Python Code
  • Debugging
  • Tests
  • Jupyter Notebook
  • Summary
  • Top

Introduction

As discussed in my guide Visual Studio Code for Software Development, one of the advantages of Visual Studio Code is the power and flexibility enabled by extensions. You can find extensions either from inside the editor or by going to the Visual Studio Code Marketplace. .NET (or C#) is one of the most popular extensions. At the time of this publication, Python is the top extension for Visual Studio Code, enjoying more than twice the number of installs of the C# extension.

Visual Studio Code for Python Development (1)

This guide will discuss how to install Visual Studio Code along with the Python extension and how to use the two together as a powerful development tool.

Installing the Python Extension

While you could develop Python apps using the default installation of Visual Studio Code, the Python extension will make it much easier. Open the Extensions pane with Ctrl-Shift-X / Cmd-Shift-X on macOS, or click the fifth icon down in the sidebar.

Visual Studio Code for Python Development (2)

At the top of the pane, search for Python in the list of extensions.

Visual Studio Code for Python Development (3)

The one you want is from Microsoft. It will have more downloads than all the others because it is currently the most popular extension for Visual Studio Code. Click the green install button and the extension will be installed.

The Python extension adds many features, such as

  • Tab completion
  • Code hints
  • Debugging
  • Linting
  • Code navigation
  • Testing
  • Jupyter notebook support

Virtual Environments

The example in this guide assumes that you have Python installed and know something about the language. This guide will not go into specifics about Python basics or virtual environments. But if you have a virtual environment in the directory that is open in the Explorer, Visual Studio Code can detect it and associate it within the editor. Open the Command Palette and search for Python: Select Interpreter.

Visual Studio Code for Python Development (4)

This will bring up a list of detected virtual environments.

Visual Studio Code for Python Development (5)

In this screenshot, there are a lot of environments on the system. But you will select the one that you created in the current directory. After that, when you open a new terminal window, the activation script for the virtual environment will run. It even detects the shell and selects the appropriate script!

Visual Studio Code for Python Development (6)

Editing Python Code

When opening a Python file for the first time in a directory, Visual Studio Code will prompt you to install a linter.

Visual Studio Code for Python Development (7)

Click Install and Visual Studio Code will open another terminal, activate the virtual environment, and pip install a linter. The linter will be used to detect errors in your code that will be displayed inside of the editor window.

Visual Studio Code provides tab completion and code hints for Python code. Notice it will detect built-in modules from the Python Standard Library:

Visual Studio Code for Python Development (8)

As well as third party modules installed with pip, such as flask (there is also snippet support!):

Visual Studio Code for Python Development (9)

And user-defined code too! It also handles indentation which you can configure to PEP-8 or your own style:

Visual Studio Code for Python Development (10)

Debugging

The Python extension also supports debugging inside of Visual Studio Code. Before debugging, you'll need to create a launch.json file to configure Visual Studio Code. This is done via the Command Palette with the Debug: Open launch.json command. Select the Python environment.

Visual Studio Code for Python Development (11)

Next select Python File to debug the currently open file.

Visual Studio Code for Python Development (12)

This will create a launch.json file in the .vscode directory in the root of the project. Set a breakpoint in a Python file by clicking to the left of the line numbers. A red dot will appear. Now switch to the Debug panel with the shortcut Ctrl-Shift-D / Cmd-Shift-D on macOS. Make sure that the configuration Python: Current File is selected in the dropdown box at the top and press the green Run button.

Visual Studio Code for Python Development (13)

The interpreter will execute the current file and stop on the line with the breakpoint. You can inspect the current values in scope in the Variables pane in the sidebar. You can set expressions in the Watch pane as well. Notice the at the top of the editor are the familiar controls for Continue, Step Over and other debugging tasks.

If you are developing web apps with Flask or Django, you can debug those in Visual Studio Code as well. In the Debug Pane select Add Configuration.

Visual Studio Code for Python Development (14)

The launch.json file will open and prompt you for the type of configuration to add. Select Python.

Visual Studio Code for Python Development (15)

This will bring up the configuration selection list in the Command Palette. Select Flask.

Visual Studio Code for Python Development (16)

You will be prompted for the path to the app. In this example, the app is in a file named two.py.

Visual Studio Code for Python Development (17)

Inside of two.py, select the Python: Flask option in the Debug panel, and a breakpoint inside of the code.

Visual Studio Code for Python Development (18)

Press the Run button. Go to http://127.0.0.1:5000 and the code will break on line 10. Notice the variables in scope can be inspected.

Visual Studio Code for Python Development (19)

Tests

The extension can also detect and run Python tests using unittest, pytest or nose. This example uses unittest as it's part of the Python Standard Library. Here is a simple method to run a test on:

1import random2import string345def generate_password(min_length = 8):6 password = ''7 for _ in range(min_length):8 next = random.choice(string.ascii_letters + string.digits)9 password += next10 return password

python

Then include a test file:

1# filename password_test.py2import password3import unittest45class PasswordTests(unittest.TestCase):def test_password_length_16(self):6 self.assertEqual(len(password.generate_password(16)), 16)78if __name__ == '__main__':9 unittest.main()

python

This simple test merely checks that the length of the generated password is the same as the value passed to the generate_password function. Open the Command Palette and search for Python: Configure Tests. You'll be asked to select a test framework, unittest in this case (no pun intended).

Visual Studio Code for Python Development (20)

Next, select the location of tests. For this simple example the root of the project will suffice.

Visual Studio Code for Python Development (21)

Finally, select a pattern that will identify files with tests. The test file for this example ends with _test.py so select the option for *_test.py.

Visual Studio Code for Python Development (22)

By installing the Test Explorer UI extension by Holger Benl, you can run the detected tests inside of the editor. Open up the Test pane (the beaker icon) to see a list of the detected tests. Click Run All Tests or open the Command Palette and search for Python: Run All Tests. The results will be shown in the Test pane and the unittest output shown at the bottom of the window.

Visual Studio Code for Python Development (23)

Changing 16 to 15 for the expected value in test_password_length will make the test fail.

Visual Studio Code for Python Development (24)

Jupyter Notebook

The Python extension provides support for Jupyter notebook. This is a very popular tool with data scientists. To create a new notebook file, open the Command Palette and search for Python: Create New Blank Jupyter Notebook. You may be prompted to install the ipykernel library which is required for Juypter support.

Visual Studio Code for Python Development (25)

Visual Studio Code will start a Jupyter notebook session and show the notebook in the editor.

Visual Studio Code for Python Development (26)

Enter code into the cells and click the green Run button to execute the cell, or press Shift-Enter.

Visual Studio Code for Python Development (27)

Cells can also contain markdown text by pressing the Markdown button. If you are working with a package like matplotlib, you can even display visualizations inline.

Visual Studio Code for Python Development (28)

You can also export and import notebook files from other Jupyter notebook implementations such as Google Colab and Azure Notebooks.

Finally, right click in any Python file and select Run Current File in Python Interactive Window to open an interactive Python console.

Visual Studio Code for Python Development (29)

The file will be executed and any members available at the prompt in the bottom of the interactive console.

Visual Studio Code for Python Development (30)

You can also execute just the current line or selection in the file by pressing Ctrl-Enter.

Summary

This is just scratching the surface of what Visual Studio Code can do for Python developers. This guide did not get into Django or Azure support, remote development, or the other languages, such as JavaScript or SQL, that you might use while developing a Python app. Still, you should be able to see that Visual Studio Code is a very flexible and powerful tool for developing Python apps and more. The community around Visual Studio Code is growing and you can find support and extensions for almost anything you need. Check out the Visual Studio Code site and Github repo for details. Thanks for reading!

Top Articles
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated: 10/01/2022

Views: 6042

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.