- Editing Python in Visual Studio Code
- Autocomplete and IntelliSense
- Customize IntelliSense behavior
- Enable IntelliSense for custom package locations
- Troubleshooting
- Quick Fixes
- Run Selection/Line in Terminal (REPL)
- Formatting
- General formatting settings
- Formatter-specific settings
- Troubleshooting
- Refactoring
- Extract Variable
- Extract Method
- Sort Imports
- Python in Visual Studio Code
- Intro to CS at Harvey Mudd College
- Why Visual Studio Code?
- Classroom settings
- Integrated Terminal
- Python Extension Pack
- Free Python and Data Science lessons
- NASA-inspired lessons
- Learn Python with Over The Moon
- Wonder Woman-inspired lessons
- Python in Notebooks
- Set up your Python beginner development environment
Editing Python in Visual Studio Code
The Python extension provides many features for editing Python source code in Visual Studio Code:
Autocomplete and IntelliSense
Autocomplete and IntelliSense are provided for all files within the current working folder and for Python packages that are installed in standard locations.
While editing, you can right-click different identifiers to take advantage of several convenient commands
Go to Definition ( F12 ) jumps from your code into the code that defines an object. This command is helpful when you’re working with libraries.
Peek Definition ( ⌥F12 (Windows Alt+F12 , Linux Ctrl+Shift+F10 ) ), is similar, but displays the definition directly in the editor (making space in the editor window to avoid obscuring any code). Press Escape to close the Peek window or use the x in the upper right corner.
Go to Declaration jumps to the point at which the variable or other object is declared in your code.
Peek Declaration is similar, but displays the declaration directly in the editor. Again, use Escape or the x in the upper right corner to close the Peek window.
Customize IntelliSense behavior
To customize the behavior of the analysis engine, see the code analysis settings and autocomplete settings.
You can also customize the general behavior of autocomplete and IntelliSense, even to disable these features entirely. See Customizing IntelliSense.
Tip: Check out the IntelliCode extension for VS Code (preview). IntelliCode provides a set of AI-assisted capabilities for IntelliSense in Python, such as inferring the most relevant auto-completions based on the current code context. For more information, see the IntelliCode for VS Code FAQ.
Enable IntelliSense for custom package locations
To enable IntelliSense for packages that are installed in other, non-standard locations, add those locations to the python.autoComplete.extraPaths collection in the settings file (the default collection is empty). For example, you might have installed Google App Engine installed in custom locations, specified in app.yaml if you use Flask. In this case, you’d specify those locations as follows:
Windows:
macOS/Linux:
The python.autoComplete.addBrackets setting (default false ) also determines whether VS Code automatically adds parentheses ( () ) when autocompleting a function name. For example, if you set addBrackets to true :
and then write import os followed by os.getc , you’ll see autocomplete for os.getcwd . Selecting that auto-complete adds os.getcwd() to your source code and place the cursor inside the parentheses. When the setting is false, only os.getcwd is added to the file.
For more on IntelliSense generally, see IntelliSense.
Troubleshooting
If autocomplete and IntelliSense are not working for a custom module, check the following causes:
Cause | Solution |
---|---|
The path to the python interpreter is incorrect | Check the pythonPath setting. Restart VS Code if you make a correction. |
The custom module is located in a non-standard location (not installed using pip). | Add the location to the python.autoComplete.extraPaths setting and restart VS Code. |
Quick Fixes
The add imports Quick Fix allows you to quickly complete import statements. Begin by typing a package name within the editor and you will notice a Code Action is available to automatically complete the line of source code (as long as you have the module installed within the environment). Hover over the text (marked with a squiggle) and then select the Code Action light bulb when it appears. You can then select from a list of potential imports. Note that the functionality in the below examples is provided by the Pylance language server.
The add imports Code Action also recognizes some of the popular abbreviations for the following common Python packages: numpy as np, tensorflow as tf, pandas as pd, matplotlib.pyplot as plt, matplotlib , as mpl, math as m, scipi.io as spio, and scipy as sp, panel as pn, and holoviews as hv.
The import suggestions list is ordered with import statements for packages (or modules) at the top, followed by statements for additional modules and/or members (classes, objects, etc.) from specified packages.
Run Selection/Line in Terminal (REPL)
The Python: Run Selection/Line in Python Terminal command ( Shift+Enter ) is a simple way to take whatever code is selected, or the code on the current line if there is no selection, and run it in the Python Terminal. An identical Run Selection/Line in Python Terminal command is also available on the context menu for a selection in the editor.
VS Code automatically removes indents based on the first non-empty line of the selection, shifting all other lines left accordingly.
Source code that runs in the terminal/REPL is cumulative until the current instance of the terminal is closed.
The command opens the Python Terminal if necessary; you can also open the interactive REPL environment directly using the Python: Start REPL command. (Initial startup might take a few moments especially if the first statement you run is an import .)
On first use of the Python: Run Selection/Line in Python Terminal command, VS Code may send the text to the REPL before that environment is ready, in which case the selection or line is not run. If you encounter this behavior, try the command again when the REPL has finished loading.
Formatting
Formatting makes code easier to read by human beings by applying specific rules and conventions for line spacing, indents, spacing around operators, and so on (see an example on the autopep8 page). Formatting doesn’t affect the functionality of the code itself. (Linting, on the other hand, analyzes code for common syntactical, stylistic, and functional errors as well as unconventional programming practices that can lead to errors. Although there is a little overlap between formatting and linting, the two capabilities are complementary.)
The Python extension supports source code formatting using either autopep8 (the default), black, or yapf.
General formatting settings
Setting (python.formatting.) | Default value | Description |
---|---|---|
provider | «autopep8» | Specifies the formatter to use, either «autopep8», «yapf», or «black». |
Formatter-specific settings
The following settings apply to the individual formatters. The Python extension looks in the current pythonPath for the formatter. To use a formatter in another location, specify that location in the appropriate custom path setting. The pip install commands may require elevation.
Formatter | Install steps | Arguments setting (python.formatting.) | Custom path setting (python.formatting.) |
---|---|---|---|
autopep8 | pip install pep8 pip install —upgrade autopep8 | autopep8Args | autopep8Path |
black (see note) | pip install black | blackArgs | blackPath |
yapf | pip install yapf | yapfArgs | yapfPath |
Note: By default, the Black formatter can’t be installed when a Python 2 environment is active. Attempting to do so may display the message «Formatter black is not installed. Install?». If you try to install Black in response, another message appears saying «Could not find a version that satisfies the requirement black’ No matching distribution found for black.»
To work around this issue and use the Black formatter with Python 2, first install Black in a Python 3 environment. Then set the python.formatting.blackPath setting to that install location.
When using custom arguments, each top-level element of an argument string that’s separated by space on the command line must be a separate item in the args list. For example:
In the second example, the top-level element
Troubleshooting
If formatting fails, check the following possible causes:
Cause | Solution |
---|---|
The path to the python interpreter is incorrect. | Check the pythonPath setting. |
The formatter is not installed in the current environment. | Open a command prompt, navigate to the location specified in the pythonPath setting, and run pip install for the formatter. |
The path to the formatter is incorrect. | Check the value of the appropriate python.formatting. Path setting. |
Custom arguments for the formatter are incorrect. | Check that the appropriate python.formatting. Path setting does not contain arguments, and that python.formatting. Args contains a list of individual top-level argument elements such as «python.formatting.yapfArgs»: [«—style», « |
Pop up with warning message Black does not support the «Format Select» command. | black does not support formatting sections of code, it can be prevented with the following settings «[python]»: <"editor.formatOnPaste": false, "editor.formatOnSaveMode": "file">. |
Refactoring
The Python extension adds the following refactoring functionalities: Extract Variable, Extract Method, and Sort Imports.
Extract Variable
Extracts all similar occurrences of the selected text within the current scope, and replaces it with a new variable.
You can invoke this command by selecting the line of code you wish to extract as a variable and then clicking on the light-bulb that is displayed next to it.
Extract Method
Extracts all similar occurrences of the selected expression or block within the current scope, and replaces it with a method call.
You can invoke this command by selecting the lines of code you wish to extract as a method and then clicking on the light-bulb that is displayed next to it.
Sort Imports
Sort Imports uses the isort package to consolidate specific imports from the same module into a single import statement and to organize import statements in alphabetical order.
- Right-click in editor and select Sort Imports (no selection is required)
- Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), then Python Refactor: Sort Imports
- Assign a keyboard shortcut to the python.sortImports command
Custom arguments to isort are specified in the python.sortImports.args setting, where each top-level element, as separated by spaces on the command line, is a separate item in the array:
To use a custom isort script, use the python.sortImports.path setting to specify the path.
Further configurations can be stored in an .isort.cfg file as documented on isort configuration.
Note: For those migrating from isort4 to isort5, some CLI flags and config options have changed, refer to the project’s isort5 upgrade guide.
Источник
Python in Visual Studio Code
Visual Studio Code is a free source code editor that fully supports Python and useful features such as real-time collaboration. It’s highly customizable to support your classroom the way you like to teach.
«Visual Studio Code is the best balance of authenticity and accessibility. Visual Studio Code doesn’t feel ‘fake’, it’s what real software developers use. Plus, Visual Studio Code works on every OS!» — Professor Zachary Dodds from Harvey Mudd College
Read below for recommendations for extensions, settings, and links to free lessons that you can use in your classes.
Intro to CS at Harvey Mudd College
Professor Zachary Dodds is a Computer Science professor at Harvey Mudd College who teaches several introductory classes both for students new to Computer Science and students from a non-Computer Science background. He co-created the popular introduction to Computer Science class CS5, which attracts students from all backgrounds to develop programming and problem-solving skills and to build «a coherent, intellectually compelling picture of Computer Science». The class is taught with Python and uses VS Code as the recommended editor.
Why Visual Studio Code?
Professor Dodds has been recommending and using Visual Studio Code in his classes since it debuted in 2015.
«Visual Studio Code is the best balance of authenticity and accessibility. Visual Studio Code doesn’t feel ‘fake’, it’s what real software developers use. Plus, Visual Studio Code works on every OS!»
VS Code runs on Windows, macOS, Linux, and even Chromebooks.
Classroom settings
Since VS Code is easy to customize, Professor Dodds is able to tailor the editor for his students, preferring to hide IntelliSense, or code completion suggestions, so they can learn from what they type and reinforce the conceptual models being built.
Here are the settings his students use:
You can find the most up-to-date settings on his course website: CS5 — Python Tips.
Integrated Terminal
Professor Dodds also utilizes the built-in terminal heavily in his class as an introduction to running programs from the command line and navigating around their machine all within Visual Studio Code. He appreciates how «the built-in terminal panel does not try to automate too much (which, if it did, would deprive newcomers of the experience of the information-flow that’s going on).»
In the video below, the student does all of their command line and coding work in one place, such as installing Python libraries, while working on Lab 3 from the CS5 class:
Thank you, Professor Dodds, for sharing your story! If you’re interested in using VS Code to teach Python in your classes, you can get started with the Python Education Extension Pack below!
Python Extension Pack
Unsure which extensions to recommend to your students? You can point your students to the Python Education Extension Pack that contains essential and helpful extensions for the classroom. You can download the extension pack from the VS Code Marketplace:
The extension pack contains:
- Python for basic Python functionality like compiling, debugging support, linting, Jupyter Notebooks, unit tests, and more.
- Live Share to enable real-time collaboration and Live Share Audio to enable audio calls as well.
- Remote — SSH to work on remote projects (for example, to access lab machines) through SSH with full VS Code functionality.
- Markdown+Math for full LaTeX support in Markdown.
- Python Test Explorer for Visual Studio Code to visualize and run Python tests in the side bar.
- Code Runner to run snippets (selected code) and single files of any code with a single click.
Free Python and Data Science lessons
NASA-inspired lessons
This learning path enables students to use Python to explore doing analyses and projects inspired from real-world problems faced by National Aeronautics and Space Administration (NASA) scientists. View full details of the lessons under NASA-inspired Lessons.
Learn Python with Over The Moon
These space-themed lessons were inspired by the Netflix film, Over the Moon, and will introduce students to data science, machine learning, and artificial intelligence using Python and Azure. View full details on Learn Python with Over The Moon.
Wonder Woman-inspired lessons
Give an introduction to Python with «Wonder Woman 1984»-inspired lessons that help students learn about the basics like conditionals and variables. Get full lesson details under Learn Python with Wonder Woman.
Python in Notebooks
Set up your Python beginner development environment
A step-by-step guide to installing and setting up your Python and VS Code environment. View the full lesson on Microsoft Learn: Set up your Python beginner development environment with Visual Studio Code.
Источник