新的介绍内容:

YAPF:VSCode中Python文件格式化扩展的终极指南
YAPF是专门为Python文件和笔记本单元格设计的VSCode格式化扩展,旨在帮助开发者快速、有效地格式化代码。作为预览版,我们欢迎您提出任何功能需求。
支持版本: YAPF扩展支持所有当前活跃维护的Python版本,即Python 3.9及以上(截至2025年10月)。
快速开始: 要快速启用此格式化工具,请在VSCode设置中添加以下配置:
"[python]": {
"editor.formatOnSaveMode": "file",
"editor.formatOnSave": true,
"editor.defaultFormatter": "eeyore.yapf",
"editor.formatOnType": false
}使用方法:
- 安装YAPF: 推荐从pip安装最新版本的YAPF包:
pip install yapf- 选择YAPF格式化工具: 在VSCode设置中添加以下配置:
"[python]": {
"editor.defaultFormatter": "eeyore.yapf"
}- 启用保存时格式化: 在VSCode设置中添加以下配置:
"[python]": {
"editor.formatOnSave": true
}解决Python 3.8或更低版本的崩溃问题:
使用yapf.interpreter属性选择Python 3.9或更高版本的解释器,通过子进程运行此工具。
文件模式与修改模式:
- 文件模式:
"[python]": {
"editor.formatOnSaveMode": "file"
}- 修改模式:
"[python]": {
"editor.formatOnSaveMode": "modifications"
}笔记本格式化:
- 单元格执行时格式化:
"notebook.formatOnCellExecution": true- 保存时格式化:
"notebook.formatOnSave.enabled": true设置自定义YAPF样式: 自定义YAPF样式需在settings.json的全局范围内设置,不能在[python]块中。以下是两种设置样式的示例:
- 直接设置样式:
"yapf.args": ["--style", "{based_on_style: pep8, indent_width: 2}"]- 使用样式文件:
"yapf.args": ["--style", "/home/example/.yapf"]为Jupyter添加额外魔法函数: 默认支持以下魔法函数:
"capture",
"prun",
"pypy",
"python",
"python3",
"time",
"timeit"如需添加其他魔法函数(如%matplotlib inline),请将它们添加到yapf.cellMagics属性中:
"yapf.cellMagics": ["matplotlib inline"]通过YAPF在VSCode中格式化您的Python代码,提升开发效率和代码质量。
