Edit Python code in Visual Studio Code (2023)

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.

Edit Python code in Visual Studio Code (1)

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.autoImportCompletionsaTRUEin your settings.

By default, only top level symbols/packages are suggested to be auto-imported. For example, you can seeimport matplotlibas a suggestion, but noimport matplotlib.pyplotby default. However, you can customize this behavior via thepython.analysis.packageIndexDepthsconfiguration (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.extraPathscollection in yourconfiguration.jsonfile (default collection is empty). For example, you can have Google App Engine installed in custom locations specified inapp.yamlif you use Flask. In this case, you would specify these locations as follows:

(Video) Powerful VSCode Tips And Tricks For Python Development And Design


"python.analysis.extraPaths": [ "C:/Program Files (x86)/Google/google_appengine", "C:/Program Files (x86)/Google/google_appengine/lib/flask-0.12"]


"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:

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.excludeAdjust to see if performance improves. Alternatively, you can try settingpython.analysis.indexingaFALSEto 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 wrongMake 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.extraPathssettings 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.

Edit Python code in Visual Studio Code (2)

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.


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 VSCode

  • statement 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.Edit Python code in Visual Studio Code (3)

This code action also recognizes some of the popular abbreviations for the following common Python packages:swellinglike np,tensorflowlike tf,pandasas pd,matplotlib.pyplotas plt,matplotlib, like mpl,mathematicslike m,scipi.ioas a spy andspylike sp,panelas pn, andholovistasas hv.

Edit Python code in Visual Studio Code (4)

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.packageIndexDepthscontext.

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 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.

(Video) Edit and Run Code in Visual Studio Code

The Python extension supports formatting source code usingautopep8(the default value),negro, oYapf.

General format settings

Standard valueDescription
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 pipcommands may require elevation.

formatterinstallation stepsargument setting
custom route configuration
autopep8pip install --update autopep8autopep8Argsautopep8Path
black (see note)pip install blackblack argumentsblack road
Yapfpip install yapfyapfArgsyapfRoute

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.blackPathadjust 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:

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 pipfor the formatter.
The path to the formatter is incorrect.Check the value of the respectivepython.formatting.<formateador>Rutacontext.
The custom arguments for the formatter are incorrect.check if the correctpython.formatting.<formateador>Rutaconfiguration contains no arguments, and thatpython.formatting.<formateador>Argscontains 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.negrodoes 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.


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.

Edit Python code in Visual Studio Code (5)

extraction method

Extracts all similar occurrences of the selected expression or block within the current scope and replaces them with a method call.

(Video) How to setup Python for VSCode in 2023 in 5mins! | Install Python and Setup VSCode for Windows 10

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.

Edit Python code in Visual Studio Code (6)

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.

Edit Python code in Visual Studio Code (7)

Sort imports

Sort Imports uses the isort package to consolidate specific imports from the same module into a single module.matterdeclaration and organizematterstatements 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 topython.sortImportsdomain

Edit Python code in Visual Studio Code (8)

Custom arguments for isorting are specified in thepython.sortImports.argsconfiguration, 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.boxconfiguration to specify the path.

Other settings can be stored in a.isort.cfgfile 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.


(Video) The 5 Best Python IDE's and Editors


1. Visual Studio Code (Windows) - Setting up a Python Development Environment and Complete Overview
(Corey Schafer)
2. Learn Visual Studio Code in 7min (Official Beginner Tutorial)
(Visual Studio Code)
3. Setting Up VSCode For Python Programming
(Traversy Media)
4. Python IDLE vs Pycharm vs VSCode - Best Python Code Editor - Learn Python Codes Python Tutorial
(Code Jana)
5. How to Run Python in Visual Studio Code on Windows 10 2022 Best IDE
(Tech Decode Tutorials)
6. How to set up Python on Visual Studio Code in 2021
(Kenny Yip Coding)
Top Articles
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated: 03/07/2023

Views: 5964

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.