Visual Studio Code for Python Development
May 15, 2020 • 10 Minute Read
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.
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.
At the top of the pane, search for Python in the list of extensions.
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
This guide is not going to be able to cover all of these features but will take a look a some of them.
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.
This will bring up a list of detected virtual environments.
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!
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.
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:
As well as third party modules installed with pip, such as flask (there is also snippet support!):
And user-defined code too! It also handles indentation which you can configure to PEP-8 or your own style:
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.
Next select Python File to debug the currently open file.
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.
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.
The launch.json file will open and prompt you for the type of configuration to add. Select Python.
This will bring up the configuration selection list in the Command Palette. Select Flask.
You will be prompted for the path to the app. In this example, the app is in a file named two.py.
Inside of two.py, select the Python: Flask option in the Debug panel, and a breakpoint inside of the code.
Press the Run button. Go to https://127.0.0.1:5000 and the code will break on line 10. Notice the variables in scope can be inspected.
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:
import random
import string
def generate_password(min_length = 8):
password = ''
for _ in range(min_length):
next = random.choice(string.ascii_letters + string.digits)
password += next
return password
Then include a test file:
# filename password_test.py
import password
import unittest
class PasswordTests(unittest.TestCase):def test_password_length_16(self):
self.assertEqual(len(password.generate_password(16)), 16)
if __name__ == '__main__':
unittest.main()
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).
Next, select the location of tests. For this simple example the root of the project will suffice.
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.
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.
Changing 16 to 15 for the expected value in test_password_length will make the test fail.
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 will start a Jupyter notebook session and show the notebook in the editor.
Enter code into the cells and click the green Run button to execute the cell, or press Shift-Enter.
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.
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.
The file will be executed and any members available at the prompt in the bottom of the interactive console.
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!