Formatting Python in VS Code

Formatting makes source code easier to read by human beings. By enforcing particular rules and conventions such as line spacing, indents, and spacing around operators, the code becomes more visually organized and comprehensible. You can view an example on the autopep8 page. Keep in mind, formatting doesn't affect the functionality of the code itself.

Linting helps to prevent errors by analyzing code for common syntactical, stylistic, and functional errors and unconventional programming practices. Although there is a little overlap between formatting and linting, the two capabilities are complementary.

Choose a formatter

Search the Visual Studio Marketplace for the formatter extension of your choice.

Microsoft publishes the following formatting extensions:

Formatter Extension
autopep8 https://marketplace.visualstudio.com/items?itemName=ms-python.autopep8
Black formatter https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter

Formatter extensions offered by the community:

Formatter Extension
Ruff https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff
yapf https://marketplace.visualstudio.com/items?itemName=eeyore.yapf

Furthermore, below are formatter extensions that support import sorting:

Formatter Extension
Ruff https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff
isort https://marketplace.visualstudio.com/items?itemName=ms-python.isort

Note: If you don't find your preferred formatter in the table above or in the Marketplace, you can add support for it via an extension. You can use the Python Extension Template to integrate new Python tools into VS Code.

Set a default formatter

Once you install a formatter extension, you can select it as the default formatter for Python files in VS Code by following the steps below:

  1. Open a Python file in VS Code.
  2. Right-click on the editor to display the context menu.
  3. Select Format Document With....
  4. Select Configure Default Formatter... from the drop-down menu.
  5. Select your preferred formatter extension from the list.

Alternatively, you can set it as the default formatter for all Python files by setting "editor.defaultFormatter" in your User settings.json file, under a [python] scope. You can open settings.json with the Preferences: Open User Settings (JSON) command.

For example, to set Black Formatter as the default formatter, add the following setting to your User settings.json file:

  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter"
  }

In order to set a formatter extension as an import sorter, you can set your preference under "editor.codeActionsOnSave" in your User settings.json file or your Workspace