Visual Studio Code is a powerful editing tool for Python source code. The editor includes several features to help you be productive when writing code. For more information about editing in Visual Studio Code, seebasic editionynavigation code.
In this overview, we will describe the specific editing functions provided bypython extension, including steps on how to customize these features by user and workspacesettings.
Autocompletar e IntelliSense
IntelliSense is a general term for code editing features related to code completion. Take a moment to look at the following example. Whenprintis written, notice how IntelliSense fills in the autocomplete options. The user is also presented with a list of options when he starts typing the variable calledgreetings.
AutoComplete and IntelliSense are provided for all files within the current working folder. They are also available for Python packages installed in default locations.
For more information about IntelliSense in general, seeIntelliSense.
Advice: Check aIntelliCode Extension for VS Code. IntelliCode provides a set of AI-assisted capabilities for IntelliSense in Python, such as inferring the most relevant autocompletes based on the current code context. For more information, see theIntelliCode for VS Code FAQ.
Customize IntelliSense behavior
Enabling the full set of IntelliSense features by default could end up making your development experience feel slower, so the Python extension enables a minimal set of features that allow you to be productive while still having a high-performance experience. performance However, you can customize the behavior of the verification mechanism to your liking through various settings.
Enable automatic imports
Pylanceoffers automatic import suggestions for modules in your workspace and/or packages you have installed in your environment. This allows for import statements to be automatically added as you type. Automatic imports are disabled by default, but you can enable them by settingpython.analysis.autoImportCompletions
aTRUE
in your settings.
By default, only top level symbols/packages are suggested to be auto-imported. For example, you can seeimport matplotlib
as a suggestion, but noimport matplotlib.pyplot
by default. However, you can customize this behavior via thepython.analysis.packageIndexDepths
configuration (seeIntelliSense Setup Documentationlearn more). User-defined symbols (those that do not come from installed packages or libraries) are only automatically imported if they have already been used in files opened in the editor. Otherwise, they will only be available through theadd imports Quick Fix.
Enable IntelliSense for custom package locations
To enable IntelliSense for packages installed in non-default locations, add those locations to thepython.analysis.extraPaths
collection in yourconfiguration.json
file (default collection is empty). For example, you can have Google App Engine installed in custom locations specified inapp.yaml
if you use Flask. In this case, you would specify these locations as follows:
Windows:
"python.analysis.extraPaths": [ "C:/Program Files (x86)/Google/google_appengine", "C:/Program Files (x86)/Google/google_appengine/lib/flask-0.12"]
MacOS/Linux:
"python.analysis.extraPaths": [ "~/.local/lib/Google/google_appengine", "~/.local/lib/Google/google_appengine/lib/flask-0.12"]
To see the complete list of available IntelliSense controls, you can refer to the Python extensioncode analysis setupyautocomplete settings.
You can also customize the general behavior of autocomplete and IntelliSense, including disabling features altogether. You can learn more atIntelliSense Customization.
IntelliSense Troubleshooting
For autocomplete and IntelliSense issues, check the following causes:
Cause | Solution |
---|---|
Pylance seems slow or memory intensive when working in a large workspace. | If there are subfolders that you know can be excluded from Pylance scanning, you can add their paths to thepython.analysis.exclude Adjust to see if performance improves. Alternatively, you can try settingpython.analysis.indexing aFALSE to disable the Pylance indexer (To use: This will also affect the autocompletions and import experience. Learn more about indexing atcode analysis setup). |
Pylance only offers top level symbol options when adding imports. | Try increasing the depth to which Pylance can index your installed libraries via thepython.analysis.packageIndexDepths . To checkcode analysis setup. |
Path to python interpreter is wrong | Make sure you have selected a valid interpreter path by running thePython: select interpretercommand (seeenvironments). |
The custom module is in a non-default location (not installed with pip). | Add the location topython.autoComplete.extraPaths settings and restart VS Code. |
Improve conclusions with AI
GitHub co-pilotis an AI-based code completion tool that helps you write code faster and smarter. you can use theGitHub Copilot Extensionin VS Code to generate code or learn from the code it generates.
GitHub Copilot provides suggestions for many languages and a wide range of frameworks, and works especially well for Python, JavaScript, TypeScript, Ruby, Go, C#, and C++.
You can learn more about how to get started with Copilot atCo-pilot documentation.
Navigation
During editing, you can right-click on different handles to take advantage of various convenient commands.
Go to Definition(F12) jumps from your code to the code that defines an object. This command is useful when working with libraries.
definition at a glance(⌥F12(windowsAlt+F12, linuxCtrl+Shift+F10)), is similar, but displays the definition directly in the editor (creating space in the editor window to avoid hiding code). PressEscapeto close the Peek window or use thexat the top right corner.
Go to Declarationjumps to the point where the variable or other object is declared in your code.
(Video) Getting Started with Python in Visual Studio Code | Python with VSCodestatement at a glanceis similar, but displays the declaration directly in the editor. Again, useEscapeor thexin the upper-right corner to close the Peek window.
quick fixes
The quick fix for adding imports when using Pylance allows you to quickly complete import statements. First, start typing a package name into the editor. You'll notice that a code action is available to automatically complete the line of source code (as long as you have the module installed in the environment). Hover over the text (marked with a squiggle) and select the action code light bulb when it appears. You can then select from a list of possible imports.
This code action also recognizes some of the popular abbreviations for the following common Python packages:swelling
like np,tensorflow
like tf,pandas
as pd,matplotlib.pyplot
as plt,matplotlib
, like mpl,mathematics
like m,scipi.io
as a spy andspy
like sp,panel
as pn, andholovistas
as hv.
The list of import suggestions is ordered with import instructions for packages (or modules) at the top. It will also include declarations for more modules and/or members (classes, objects, etc.) of specific packages.
As with automatic imports, only top-level symbols are suggested by default. You can customize this behavior through thepython.analysis.packageIndexDepths
context.
Execute Select/Line in Terminal (REPL)
HePython: execute select/line no terminal pythondomain (Shift+Enter) is a simple way to take any selected code, or the code on the current line if there is no selection, and run it in the Python terminal. an identicalRun select/line in Python terminalThe command is also available in the context menu for a selection in the editor.
VS Code automatically removes indents based on the first non-empty line in the selection, shifting all other lines to the left when necessary.
Source code executed 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 thePython: Start REPLdomain. (The initial initialization can take a few minutes, especially if the first instruction executed is amatter
.)
On the first use ofPython: execute select/line no terminal pythoncommand, VS Code may send the text to the REPL before the environment is ready, in which case the select or line is not executed. If you encounter this behavior, try the command again after the REPL has finished loading.
formatting
Formatting makes code easier for humans to read. Apply specific rules and conventions for line spacing, indentation, spaces around operators, etc. You can see an example atautopep8page. Note that the format does not affect the functionality of the code itself.
downhelps prevent errors by analyzing code for common syntactic, stylistic, and functional errors and unconventional programming practices. While there is little overlap between formatting and linting, the two features are complementary.
The Python extension supports formatting source code usingautopep8(the default value),negro, oYapf.
General format settings
Context (format.python.) | Standard value | Description |
---|---|---|
supplier | "autopep8" | Specifies the formatter to use, "autopep8", "yapf", or "black". |
Formatter specific settings
The following settings apply to individual formatters. The Python extension looks for the formatter in the selected interpreter. To use a formatter in another location, specify that location in the appropriate custom path setting. Heinstall pip
commands may require elevation.
formatter | installation steps | argument setting (format.python.) | custom route configuration (format.python.) |
---|---|---|---|
autopep8 | pip install --update autopep8 | autopep8Args | autopep8Path |
black (see note) | pip install black | black arguments | black road |
Yapf | pip install yapf | yapfArgs | yapfRoute |
To use: By default, the Black formatter cannot be installed when a Python 2 environment is active. Attempting to do so may display the message "The black formatter is not installed. Install?". If you try to install Black in response, you will get another message saying "Could not find a version that satisfies the requirement for black' No matching distribution found for black".
To work around this problem and use the Black formatter with Python 2, first install Black in a Python 3 environment.
python.formatting.blackPath
adjust to that installation location.
When using custom arguments, each top-level item in a space-separated argument string on the command line must be a separate item in the argument list. For example:
"python.formatting.autopep8Args": ["--max-line-length","120","--experimental"],"python.formatting.yapfArgs": ["--style","{based_on_style: chrome, indent width: 2}"],"python.formatting.blackArgs": ["--line length","100"]
In the second example, the top-level element{based_on_style: chrome, dash_width: 2}
is a single value enclosed in square brackets, so spaces within that value do not delimit a separate element.
Troubleshooting Formatting
If formatting fails, check the following possible causes:
Cause | Solution |
---|---|
The path to the python interpreter is incorrect. | Make sure you have selected a valid interpreter path by running thePython: select interpreterdomain. |
The formatter is not installed in the current environment. | Open a command prompt, navigate to the location where the selected interpreter is located, and runinstall pip for the formatter. |
The path to the formatter is incorrect. | Check the value of the respectivepython.formatting.<formateador>Ruta context. |
The custom arguments for the formatter are incorrect. | check if the correctpython.formatting.<formateador>Ruta configuration contains no arguments, and thatpython.formatting.<formateador>Args contains a list of individual elements of top-level arguments, such as"python.formatting.yapfArgs": ["--style", "{based_on_style: chromium, indent_width: 2}"] . |
Pop-up window with warning messageBlack does not support the "Select Format" command. | negro does not support formatting code sections, can be avoided with the following configuration"[python]": {"editor.formatOnPaste": false, "editor.formatOnSaveMode": "file"} . |
To use: If you don't see your preferred formatter in the list above, you can add support via an extension. HePython extension templatemakes it easy to integrate new Python tools into VS Code.
restructuring
The Python extension adds the following refactoring features:extract variable,extraction method,Change module name, youSort imports.
extract variable
Extracts all similar occurrences of selected text within the current scope and replaces them with a new variable.
You can invoke this command by selecting the line of code you want to extract as a variable. Then select the bulb shown next to it.
extraction method
Extracts all similar occurrences of the selected expression or block within the current scope and replaces them with a method call.
You can invoke this command by selecting the lines of code you want to extract as a method. Then select the bulb shown next to it.
Change module name
After renaming a Python file/module, Pylance can find all instances that need to be updated and provide a preview of all changes.
To customize which references should be updated, you can toggle the checkboxes at the line or file level underRefactoring Preview. After making your selections, you can selectapply refactoringoDismiss refactoring.
Sort imports
Sort Imports uses the isort package to consolidate specific imports from the same module into a single module.matter
declaration and organizematter
statements in alphabetical order.
Invoked by:
- Right-click in the editor and selectSort imports(no selection required)
- command palette (⇧⌘P(Windows,LinuxCtrl+Shift+P)), thenPython refactoring: sort imports
- Assign a keyboard shortcut to
python.sortImports
domain
Custom arguments for isorting are specified in thepython.sortImports.args
configuration, where each top-level element, separated by spaces on the command line, is a separate element in the array:
"python.sortImports.args": ["-rc","--atomic"],
To use a custom isort script, use thepython.sortImports.box
configuration to specify the path.
Other settings can be stored in a.isort.cfg
file as documented inrating settings.
To use: For those migrating from isort4 to isort5, some CLI flags and configuration options have changed, see the projectisort5 upgrade guide.
Next steps
- down- Enable, configure and apply various Python linters.
- debugging- Learn to debug Python locally and remotely.
- Evidence- Set up test environments and discover, run and debug tests.
- basic edition- Learn about VS Code's powerful editor.
- navigation code- Quickly move through your source code.
- IntelliSense- Learn about IntelliSense features.
- Suporte a Jupyter- Learn how to get started with Jupyter Notebooks.
- Python extension template- Create an extension to integrate your favorite Python tools.
11/03/2022