Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 629
Mikhail_Sam Avatar asked Jan 20 '20 10:01

Mikhail_Sam


People also ask

How do I use black format in VS Code?

Go to settings in your VS-Code typing “Ctrl + ,” or clicking at the gear on the bottom left and selecting “Settings [Ctrl+,]” option. Type “format on save” at the search bar on top of the Settings tab and check the box. Search for “python formatting provider” and select “black”.

How do I beautify Python code in Visual Studio Code?

The code formatting is available in Visual Studio Code (VSCode) through the following shortcuts or key combinations: On Windows Shift + Alt + F. On macOS Shift + Option + F. On Linux Ctrl + Shift + I.


1 Answers

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.

like image 133
Mikhail_Sam Avatar answered Oct 21 '22 23:10

Mikhail_Sam