在VS Code中格式化Python

格式化使源代码更易于人类阅读。通过强制执行特定的规则和约定,如行间距、缩进和操作符周围的间距,代码在视觉上变得更加有条理和易于理解。您可以在autopep8页面上查看一个示例。请记住,格式化不会影响代码本身的功能。

Linting 通过分析代码中的常见语法、风格和功能错误以及非传统的编程实践,帮助预防错误。尽管格式化和linting之间有一些重叠,但这两项功能是互补的。

选择一个格式化工具

VS Code Marketplace中搜索您选择的格式化程序扩展。

微软发布了以下格式化扩展:

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 Extension
Ruff https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff
yapf https://marketplace.visualstudio.com/items?itemName=eeyore.yapf

此外,以下是支持导入排序的格式化程序扩展:

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

注意: 如果您在上面的表格或市场中找不到您喜欢的格式化程序,您可以通过扩展来添加支持。您可以使用Python 扩展模板将新的 Python 工具集成到 VS Code 中。

设置默认格式化程序

一旦你安装了一个格式化扩展,你可以按照以下步骤在VS Code中将其选为Python文件的默认格式化工具:

  1. 在 VS Code 中打开一个 Python 文件。
  2. 右键点击编辑器以显示上下文菜单。
  3. 选择使用...格式化文档
  4. 从下拉菜单中选择配置默认格式化程序...
  5. 从列表中选择您偏好的格式化程序扩展。

或者,您可以通过在您的用户settings.json文件中的[python]范围内设置"editor.defaultFormatter",将其设置为所有Python文件的默认格式化程序。您可以使用首选项:打开用户设置(JSON)命令打开settings.json

例如,要将Black Formatter设置为默认格式化程序,请将以下设置添加到您的用户settings.json文件中:

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

为了将格式化扩展设置为导入排序器,您可以在用户settings.json文件或工作区settings.json文件中的[python]范围内设置您的偏好。您可以使用首选项:打开用户设置(JSON)首选项:打开工作区设置(JSON)命令分别打开这些settings.json文件。这将为所有Python文件启用保存时的导入排序。

例如,要将Ruff设置为您首选的导入排序工具,您可以将以下设置添加到您的用户settings.json或工作区settings.json文件中:

{
  "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports.ruff": "explicit"
    }
  }
}

格式化你的代码

你可以通过右键点击编辑器并选择格式化文档来格式化你的代码,或者使用⇧⌥F (Windows Shift+Alt+F, Linux Ctrl+Shift+I)键盘快捷键。

您还可以将以下设置添加到您的用户settings.json文件中,以便在保存时启用代码格式化:

  "[python]": {
    "editor.formatOnSave": true
  }

通用格式设置

您可以参考每个格式化程序扩展的README以获取有关支持的设置的更多详细信息。大多数格式化程序扩展支持以下设置:

Setting Suffix
Default value Description
args [] Arguments to be passed to the formatter. Each argument should be passed as a separate string in the array.
For example:
black-formatter.args: ["--line-length", "100"]
importStrategy useBundled When set to useBundled, the extension uses the version of the tool that it ships with. When set to fromEnvironment, it attempts to load from your selected Python environment first, otherwise it falls back to the bundled version.
path "" Path to the formatter binary to be used for formatting. Note: Using this option may slow down formatting.
interpreter [] When set to a path to a Python executable, the extension will use that to launch the formatter server and its subprocesses.
showNotifications off Controls when notifications are displayed by the extension. Supported values are off, always, onError, and onWarning.

故障排除格式化

如果格式化失败,请检查以下可能的原因:

Problem Solution
There are multiple formatters available for Python files. Set the default formatter by following the instructions in the section above.
No "Format Document With..." option is available. If you don't see this option in the context menu, it's likely you don't have a formatter extension installed or enabled in VS Code. Reference the Choose a Formatter section to see how you can install a Python formatter extension.
Custom arguments for the formatter are incorrect. Check that the appropriate <formatter>.path setting does not contain arguments, and that <formatter>.args contains a list of individual top-level argument elements.
The "You have deprecated linting or formatting settings" notification is displayed. If you are seeing this notification, it means you have settings such as python.linting or python.formatting in VS Code. These settings are no longer supported by the Python extension, as linting and formatting support has been migrated to tools extensions.
The Format Selection command fails when using Black Formatter. black does not support formatting sections of code. To work around this limitation, you can disable format on paste and set formatOnSave to format the whole file with the following settings: "[python]": {"editor.formatOnPaste": false, "editor.formatOnSaveMode": "file"}.
Formatting doesn't work even though I have a formatter extension installed. Formatting can fail for various reasons, such as syntax issues in your code, an unsupported version of Python is used, or the formatter isn't configured correctly. Check the formatter extension's Output channel to understand why the formatter has failed (run the Output: Focus on Output command in the Command Palette, and then select the formatter extension channel).

注意: 如果您在上面没有找到您喜欢的格式化程序,您可以通过扩展添加支持。Python 扩展模板使得将新的 Python 工具集成到 VS Code 中变得容易。

下一步