Search code examples
pythonvisual-studio-codeintellisensepylintyapf

How to use yapf (or black) in VSCode


I installed yapf using:

conda install yapf

and add next lines in my .vscode/settings.json file:

{
    //"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,
}

But I can't understand how to use it - it doesn't show any error in a bad-formatted script:

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

Solution

  • 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.