How to use yapf (or black) in VSCode

The problem was in wrong settings. To use yapf, black or autopep8 you need:

  1. Install yapf / black / autopep8 (pip install black)
  2. Configure .vscode/settings.json in the next way:

part of the file:

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

Key option - "editor.formatOnSave": true, this mean yapf formats your document every time you save it.


Extending @Mikhail_Sam answer. You might want to use a separate config file as I like. This way you are decoupling your project settings from VS Code IDE. To do this you need to create .style.yapf:

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

Add rules to .style.yapf, for example:

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

Don't forget to remove from your VS code settings.json the following setting. They override .style.yapf:

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

My other VS Code settings in 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,

According to the YAPF documentation: YAPF will search for the formatting style in the following manner:

  1. Specified on the command line >> VS Code settings.json
  2. In the [style] section of a .style.yapf file in either the current directory or one of its parent directories.
  3. In the [yapf] section of a setup.cfg file in either the current directory or one of its parent directories.
  4. In the [style] section of a ~/.config/yapf/style file in your home directory.
  5. If none of those files are found, the default style is used (PEP8).