18

我使用以下方法安装了 yapf:

conda install yapf

.vscode/settings.json并在我的文件中添加下一行:

{
    //"python.linting.pylintEnabled": true,
    //"python.linting.pycodestyleEnabled": false,
    //"python.linting.flake8Enabled": true,
    "python.formatting.provider": "yapf",
    "python.formatting.yapfArgs": [
        " — style",
        "{based_on_style: pep8, indent_width: 4}"
    ],
    "python.linting.enabled": true,
}

但我不明白如何使用它 - 它在格式错误的脚本中没有显示任何错误:

import pandas as pd

class MyClass(object):
    def __init__(self, some_value: int):
        self.value = some_value
    def one_more_function(self, another_value):
        print(another_value)
myObject = MyClass(45)
myObject.one_more_function(2)
my__object2 = MyClass(324)

    print('ok')
def some_foo():
    """
    """
    pass
4

3 回答 3

27

问题出在错误的设置中。要使用 yapf、black 或 autopep8,您需要:

  1. 安装 yapf / black / autopep8 (pip install black)
  2. 配置.vscode/settings.json方式如下:

文件的一部分:

{
    "python.linting.enabled": true,
    "python.linting.pylintPath": "pylint",
    "editor.formatOnSave": true,
    "python.formatting.provider": "yapf", // or "black" here
    "python.linting.pylintEnabled": true,
}

关键选项 -"editor.formatOnSave": true,这意味着yapf每次保存文档时都会格式化您的文档。

于 2020-02-04T10:33:42.530 回答
10

扩展@Mikhail_Sam答案。您可能想根据我的喜好使用单独的配置文件。这样,您就可以将项目设置与 VS Code IDE 分离。为此,您需要创建.style.yapf

type null > .style.yapf   (for windows environment)
touch .style.yapf    (for MacOS, Linux environments)

向 中添加规则.style.yapf,例如:

[style]
based_on_style = google
spaces_before_comment = 4
indent_width: 2
split_before_logical_operator = true
column_limit = 80

不要忘记从您的 VS 代码中删除settings.json以下设置。他们覆盖.style.yapf

"python.formatting.yapfArgs": [
  "--style={based_on_style: google, column_limit: 80, indent_width: 2}"
],

我的其他 VS Code 设置settings.json

"[python]": {
  "editor.defaultFormatter": "ms-python.python",
  "editor.formatOnSave": true
},
"python.formatting.provider": "yapf",
"python.formatting.yapfPath": "C:\\ProgramData\\envCondaPy379\\Scripts\\yapf.exe",
"python.formatting.blackPath": "C:\\ProgramData\\envCondaPy379\\Scripts\\black.exe",
"python.linting.lintOnSave": true,
"python.linting.enabled": true,
"python.linting.pylintPath": "pylint",
"python.linting.pylintEnabled": true,

根据YAPF 文档:YAPF 将按以下方式搜索格式化样式:

  1. 在命令行中指定 >> VS Code settings.json
  2. 在当前目录或其父目录之一的 .style.yapf 文件的 [style] 部分中。
  3. 在当前目录或其父目录之一的 setup.cfg 文件的 [yapf] 部分中。
  4. 在主目录中 ~/.config/yapf/style 文件的 [style] 部分中。
  5. 如果没有找到这些文件,则使用默认样式 (PEP8)。
于 2021-02-25T22:06:16.997 回答
1

2022年的回答

如果您更喜欢“GUI”,也可以直接在设置(文件->首选项->设置)下输入这些值:

在此处输入图像描述

于 2022-02-11T10:18:25.773 回答